问题
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