[英]multiple associations in scope rails
這是我的情況。 如果當前用戶是男性,我需要從女性那里獲取問題
我有
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"})
什么都行不通
請幫幫我 :)
這是一個棘手的問題:
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`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.