Rails has_many, through, group not quite working

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"

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

class FileType < ActiveRecord::Base
  has_many :data_files

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:


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:


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))


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.

Need Your Help

Selector to apply jQuery event to two DOM ids

javascript jquery jquery-selectors

I have two select menus (#id1 and #id2) that, when validated as containing a user error, should instigate some DOM changes (remove error notice) when either one of them gets interacted with.