我只想了解rails scope。任何好的解释都会有所帮助。
我使用了一个范围试图显示:
scope :resumes_with_employments, -> {
where("id in (select resume_id from employments)")
}
我有2个用户。他们都有一份有就业的简历,但只展示了一个用户。
模型
user.rb
has_one :resume
resume.rb
belongs_to :user
has_many :employments
employment.rb
belongs_to :resume
模式
create_table "users", force: true do |t|
t.string "email",
t.string "firstname"
t.string "lastname"
t.string "city"
end
create_table "resumes", force: true do |t|
t.string "address"
t.string "postcode"
t.text "summary"
t.integer "user_id"
end
create_table "employments", force: true do |t|
t.string "companyname"
t.date "datestart"
t.date "dateend"
t.integer "resume_id"
t.string "employer_name"
t.string "employer_tel"
t.string "employer_address"
t.string "employer_location"
t.string "employer_city"
t.string "employer_postcode"
t.string "employer_email"
end
答案 0 :(得分:2)
scope :resumes_with_employments, -> {
where("id in (select resume_id from employments)")
}
将查询范围限定为id
与resume_id
表中的employments
匹配的用户。由于resume_id
与用户的id
无关,因此此范围不会返回有用的结果。
在这种情况下我会使用joins
,因为它会转换为SQL中的INNER JOIN
:
# in models/user.rb
scope :resumes_with_employments, -> { joins(resume: :employments) }
嵌套INNER JOIN
确保只有具有至少一个就业的简历的用户才能返回。由于简历可能有多个工作和INNER JOIN
的性质,您需要使用uniq
来排除重复项:
User.resumes_with_employments.uniq
或者当您想要计算具有该范围的uniq用户时:
User.resumes_with_employments.distinct.count(:id)