范围栏中的多个关联

时间:2014-05-21 20:03:41

标签: ruby-on-rails ruby ruby-on-rails-3

这是我的情况。如果当前用户是男性,我需要向女性提问:

我有

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

如何使用范围为男性检索问题? 我在文档中看到了一个例子

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

但有2个关联:question.user和user.profile

试过像这样的变种

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

没有效果

请帮帮我:)。

1 个答案:

答案 0 :(得分:2)

这是一个棘手的问题:

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

.where()方法需要一个如下格式的哈希:

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

将它映射到SQL,如下所示:

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

您的案例中发生了什么:

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`

但我们想要这样的东西(我猜):

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