Art
Art

Reputation: 77

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 :)

Upvotes: 1

Views: 375

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

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`

Upvotes: 2

Related Questions