【问题标题】:Rails has_many :through with conditions and building associationsRails has_many:通过条件和构建关联
【发布时间】:2011-10-27 10:18:54
【问题描述】:

我在建立具有条件的has_many :through 关联时遇到问题。我有这个模型:

class Contact < AR
  has_many :group_contacts
  has_many :groups, :through => :group_contacts, :conditions => {:groups => {:published => true}}
end

当我尝试从联系人实例化组时出现问题。使用上面的语法,我得到一个错误:

contact.groups.build
=> ActiveRecord::UnknownAttributeError: unknown attribute: groups

但是当我使用以下语法时它可以工作:

has_many :groups, :through => :group_contacts, :conditions => ['groups.published = ?', true]

contact.groups.build
=> #<Group id: nil, name: nil, description: nil, created_at: nil, updated_at: nil, published: true>

我在this question 中看到了对确切问题的引用。据说会为这个错误提交一张票(回到 pre-rails 3 版本)。我在rails 3.0.x 上找不到任何东西。

我使用的是 3.0.8。有没有其他人发现这个问题?

补充说明

我还发现,当我建立组时,它实际上在建立时忽略了我对关联的条件。我上面的构建有published =&gt; true 的唯一原因是因为它是数据库中的默认值。

这似乎是一种回归,其他人可以验证吗?

【问题讨论】:

  • 你的意思是不是:has_many :groups, :through =&gt; :group_contacts, :conditions =&gt; {:groups =&gt; {:published =&gt; true}}

标签: ruby-on-rails ruby-on-rails-3 activerecord has-many-through


【解决方案1】:
has_many :groups, :through => :group_contacts, :conditions => {:published => true}

has_many :groups, :through => :group_contacts, :conditions => {"groups.published" => true}

【讨论】:

  • 啊对...我完全习惯于在其他加入的模型上设置条件,即:conditions =&gt; {:some_model =&gt; {:attr =&gt; true}},但我想当条件在实际的has_many 模型上时,你不需要指定它。谢谢
猜你喜欢
  • 2012-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-27
  • 2013-05-06
相关资源
最近更新 更多