简体   繁体   中英

multiple associations in scope rails

here is my situation. I need to fetch questions from women if current user is man

i have

class Question < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :questions
  has_one :profile (profile has an attribute "sex")
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

how can i retrieve questions for men using scope ? i saw in documentation an example

Post.where(author: author)
Author.joins(:posts).where(posts: { author: author })

but have 2 associations: question.user and user.profile

tried variants like this

scope :for_men, joins(user: :profile).where(user: {profile_sex: "woman"})

nothing works

Help me please :)

That's a tricky one:

Question.joins(user: :profile).where(profiles: { sex: 'woman' })
              #^^^^ Question belongs_to :user (not multiple userS)

Question.joins(user: :profile).where(profiles: { sex: 'woman' })
                                    #^^^^^^^^ We use the table's name in the where clause

The .where() method expects a hash formatted like this:

where( { exact_table_name: { exact_column_name: 'wanted_value' } } )

To map it into SQL like this:

WHERE 'exact_table_name'.'exact_column_name' = "wanted_value"

What is happening in your case:

where(user: {profile_sex: "woman"})
# generates this SQL:
WHERE user.profile_sex = "woman"; 
# This implies you have a table called `user` with a column named `profile_sex`

But we want something like this (I guess):

where(profiles: { sex: 'woman' })
# generates this SQL:
WHERE profiles.sex = "woman";
# This implies you have a table called `profiles` with a column named `sex`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM