【问题标题】:has_many through with condition not workinghas_many 通过条件不工作
【发布时间】:2013-04-26 16:24:10
【问题描述】:

我有一个模型等级和一个模型用户。成绩和用户之间是通过协作实现的多对多关联。

在 user.rb 中

has_many :grades, through: :collaborations, source: :user

有效,但我只需要获得属性“存档”= false 的成绩

我试过了

has_many :grades, through: :collaborations, source: :user, conditions: [' archived = ? ', false]

但它需要所有的成绩,换句话说,条件被忽略了。

我可以将我的协作设置为这种条件,但协作与年级和学校处于多态关联,并且学校没有存档字段,这会导致错误。

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    试试这个

    has_many :grades, through: :collaborations, source: :user, :conditions => { archived: false}
    

    has_many :grades, through: :collaborations, source: :user, :conditions => { 'grades.archived' => false }
    

    【讨论】:

      【解决方案2】:

      这就是解决方案。显然因为协作是多态关系,所以需要指定一个source_type

       has_many :grades, through: :collaborations, source: :owner, source_type: "Grade", conditions: ['archived = ? ', false]
      

      【讨论】:

        猜你喜欢
        • 2013-08-16
        • 2012-08-03
        • 2012-06-17
        • 2017-10-09
        • 2023-03-10
        • 1970-01-01
        • 2012-08-22
        • 1970-01-01
        • 2011-08-02
        相关资源
        最近更新 更多