导轨的has_many:通过与环境和建筑协会 [英] Rails has_many :through with conditions and building associations

查看:138
本文介绍了导轨的has_many:通过与环境和建筑协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有建立一个协会是一个的has_many问题:通过与条件。我有这样的模式:

 类联系与LT; AR
  的has_many:group_contacts
  的has_many:组:通过=> :group_contacts,:条件=> {:组=> {:公布=>真正}}
结束
 

问题,当我尝试从一个接触实例一组发生。通过上面的语法,我得到一个错误:

  contact.groups.build
=> ActiveRecord的:: UnknownAttributeError:未知属性:群体
 

但是,当我用下面的语法它的工作原理:

 的has_many:组:通过=> :group_contacts,:条件=> ['groups.published =?',真]

contact.groups.build
=> #<组ID:无,名:无,说明:无,created_at:无,的updated_at:无,发表:真>
 

我看到提及确切的问题在<一个href="http://stackoverflow.com/questions/1514880/how-can-i-create-new-records-with-has-many-through-and-honor-conditions">this问题。据说一张票将针对这个漏洞(早在pre型导轨3个版本)。我找不到然而,在什么轨3.0.x的

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

其它注意事项的:

我还发现,当我在建筑群体,其建筑的时候居然忽略了我的条件上的关联。我上面构建了出版的唯一原因=&GT;真正的是因为它是默认的数据库。

这似乎是一个回归,可谁都验证这一点?

解决方案

 的has_many:组:通过=&GT; :group_contacts,:条件=&GT; {:公布=&GT;真正}
 

 的has_many:组:通过=&GT; :group_contacts,:条件=&GT; {groups.published=&GT;真正}
 

I'm having problems building an association that is a has_many :through with conditions. I have this model:

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

problem happens when I try to instantiate a group from a contact. With the above syntax, I get an error:

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

But when I use the following syntax it works:

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>

I see a reference to the exact problem in this question. It is said a ticket would be filed for this bug (back in pre- rails 3 versions). I can't find anything however on rails 3.0.x.

I'm using 3.0.8. Has anyone else found this issue?

Further Notes:

I've also found that when I'm building groups, it actually ignores my conditions on the association when building. The only reason my above build had published => true is because it's the default in the db.

This seems like a regression, can anyone else verify this?

解决方案

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

or

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

这篇关于导轨的has_many:通过与环境和建筑协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆