Rails: Finding a deeply nested association with a where clause

后端 未结 1 1889
滥情空心
滥情空心 2021-02-02 10:50

I have two models joined with a has_many :through relationship:

class Publication < ActiveRecord::Base
  has_many :publication_contributors
  has_many :contri         


        
1条回答
  •  再見小時候
    2021-02-02 10:57

    try to change your where clause :

    Publication
      .joins( :publication_contributors => :contributor )
      .where( :publication_contributors => {:contributor_type => "Author"}, 
              :contributors             => {:name => params[:authors]} ) 
    

    ActiveRecord api is not extremely consistent here : the arguments for where do not work exactly as those for joins. This is because the arguments for joins do not reflect the underlying SQL, whereas the arguments for where do.

    where accepts an hash whose keys are table names, and values are hashes (that themselves have column names as keys). It just prevents ambiguity when targetting a column that has the same name in two tables.

    This also explains why your second problem arises : the relation authors does not exist.

    0 讨论(0)
提交回复
热议问题