[英]Ruby on Rails - Using where condition for associated record
I'm trying to do a count of activities (belongs_to Students model) where the students gender (string on student) is equal to "male": 我正在尝试对学生的性别(学生的字串)等于“男”的活动(属于“学生”模型)进行计数:
@boysout = Activity.where(status: "Out",
user_id: current_user,
student: {gender: "male" }).count
This is the error: 这是错误:
SQLite3::SQLException: no such column: student.gender: SELECT COUNT(*) FROM "activities" WHERE "activities"."status" = ?
SQLite3 :: SQLException:无此类列:student.gender:从“活动”中选择COUNT(*),在“活动”中。“状态” =吗? AND "activities"."user_id" = 1 AND "student"."gender" = ?
AND“活动”。“ user_id” = 1 AND“学生”。“性别” =?
What is the correct syntax? 正确的语法是什么?
Edit: Here's the schema: 编辑:这是架构:
create_table "activities", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "student_id"
t.string "status"
t.integer "user_id"
t.index ["student_id"], name: "index_activities_on_student_id"
t.index ["user_id"], name: "index_activities_on_user_id"
end
create_table "students", force: :cascade do |t|
t.string "firstname"
t.string "gender"
t.integer "grade"
t.string "school"
t.string "teacher"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
More cleaner solution can be this :). 更清洁的解决方案可以是:)。
Assuming student has_many activities
associations:- 假设
student has_many activities
协会:
Student.includes(:activities).where(gender:"male").where( :activities => { :status => "Out", user_id: current_user.id } ).count
Have you tried with a join
? 您尝试过
join
吗?
Activity.joins(:student)
.where(status: "Out", user_id: current_user.id)
.where(student: { gender: "male" })
.count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.