Reputation: 2967
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))
Upvotes: 0
Views: 1394
Reputation: 3919
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.
Upvotes: 1