0

首先,我的模型定义:

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

所以基本上我打算拥有的是具有一个或多个数据文件的批次,每个数据文件都是特定类型的,我希望能够在一个批次中获得所有独特的文件类型。基于上述实现,我预计以下工作:

batch.file_types

但是,该group部分似乎不起作用。换句话说,文件类型列表不是唯一的,我必须在任何地方这样做:

batch.file_types.uniq

我究竟做错了什么?

编辑: 生成的 SQL 如下:

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

1 回答 1

1

试试这个:

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

另一种更高效的数据库方法是:

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

祝你好运!

Rails 4 中的 Rails 4 更新
has_many :file_types, -> { distinct }, through: :data_files

这里

于 2012-06-14T13:38:52.557 回答