【问题标题】:Rails has_many, through, group not quite workingRails has_many,通过,组不太工作
【发布时间】:2012-06-17 00:59:03
【问题描述】:

首先,我的模型定义:

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

【问题讨论】:

  • 你试过:group =&gt; :file_type_id吗?请发布生成的 SQL。
  • 在问题中添加了 SQL。谢谢

标签: ruby-on-rails ruby-on-rails-3 activerecord associations


【解决方案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, -&gt; { distinct }, through: :data_files

来自here

【讨论】:

  • 我有多个(链):through,它会抛出这个错误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
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 2011-08-02
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
相关资源
最近更新 更多