0

First off, my model definitions:

class Batch < ActiveRecord::Base
  has_many :data_files
  has_many :file_types, :through => :data_files, :group => "data_files.file_type_id"
end

class DataFile < ActiveRecord::Base
  belongs_to :batch
  belongs_to :file_type
end

class FileType < ActiveRecord::Base
  has_many :data_files
end

So basically what I intend to have are batches that have one or more data files, each data file is of a particular type and I want to be able to get all the unique file types in a batch. Based on the above implementation, I would have expected the following to work:

batch.file_types

However, the group part does not seem to be working. In other words the list of file types is not unique and I have to do this everywhere:

batch.file_types.uniq

What am I doing wrong?

EDIT: The SQL generated is as follows:

 SELECT `file_types`.* FROM `file_types` 
 INNER JOIN `data_files` ON `file_types`.id = `data_files`.file_type_id 
 WHERE ((`data_files`.batch_id = 234))
Adnan
  • 2,859
  • 4
  • 27
  • 45

1 Answers1

1

Try this:

has_many :file_types, :through => :data_files, :uniq => true

The other and more database efficient way to do is:

has_many :file_types, :through => :data_files, :select => "DISTINCT file_types.*"

Good luck!

Update for Rails 4
In Rails 4: has_many :file_types, -> { distinct }, through: :data_files

From here.

Community
  • 1
  • 1
Anil
  • 3,829
  • 1
  • 17
  • 28
  • I've a multiple (chain) `:through` and it throws me this error `Unknown key: :uniq. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table` – mariowise Oct 09 '15 at 14:12