【问题标题】:rails has_many :through with conditions on aliased associationrails has_many :通过别名关联的条件
【发布时间】:2011-12-24 02:18:10
【问题描述】:

这种配合my original questionhas_many :through有条件,但我发现了另一个问题。

鉴于这个类:

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

当我尝试将anonymous_groups 包含在contacts 中时,就会出现问题:

Contact.includes(:anonymous_groups)

ActiveRecord::StatementInvalid: PGError: ERROR: missing FROM-clause entry for table "contacts"

原因是生成的sql不正确。这类似于:

SELECT "group_contacts"."id" AS t0_r0 ... "groups"."anonymous" AS t1_r5 ... LEFT OUTER JOIN "groups" ON "groups"."id" = "group_contacts"."group_id" WHERE ("group_contacts".contact_id IN (...) AND ("contacts"."anonymous" = 'true'))

当然是意译,但请看最后的条件。它将匿名条件放在contacts 而不是groups

现在,我们可以缓解这个查询错误(我确定这是一个错误),但可以执行以下操作:

has_many :anonymous_groups, :through => :group_challenges, :source => :group, :conditions => { :groups => {:anonymous => :true} }

这将条件放在 sql 中的正确表上,但是当我尝试建立一个匿名组时,我得到了这个:

contact.anonymous_groups.build

ActiveRecord::UnknownAttributeError: 未知属性:groups.anonymous

所以它适用于查询,但不适用于构建。我很确定这是一个错误,但我想知道是否有其他人遇到过这种情况或有解决方法。

【问题讨论】:

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


    【解决方案1】:

    我认为像:conditions =&gt; "groups.anonymous = true" 这样的东西应该可以正常工作。

    【讨论】:

    • 这很奇怪,我试过这样做::conditions =&gt; {'groups.anonymous' =&gt; true},但由于同样的原因失败了。但是在直线上做它是有效的。奇怪。非常感谢
    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 2013-05-06
    • 1970-01-01
    相关资源
    最近更新 更多