has_many through with condition not working

爱⌒轻易说出口 提交于 2020-01-07 06:28:09

问题


I have a model Grade and a model User. Between grades and user is a many-to-many association through collaborations.

in user.rb

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

works, but i need to get only grades with attribute "archived" = false

i tryied

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

but it takes all the grades, in other words, the condition is ignored.

I can put in my collaborations this condition, but collaboration is in a polymorphic association with Grade and School, and a school doesn't have the archived field, and those causes an error.

Any ideas?


回答1:


Try using this

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

or

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



回答2:


This was the solution. Apparently because collaboration is a polymorphic relation, you need to specify a source_type

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


来源:https://stackoverflow.com/questions/16241015/has-many-through-with-condition-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!