1
votes

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" = ? AND "activities"."user_id" = 1 AND "student"."gender" = ?

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"
2
Join it with table STUDENT - anon
@beaconhill Can you please update the question with the schema of students and activities? And what is the significance of user_id column? Do you have another model for users? - Arun Kumar Mohan
@ArunKumar just added it! - beaconhill

2 Answers

2
votes

More cleaner solution can be this :).

Assuming student has_many activities associations:-

  Student.includes(:activities).where(gender:"male").where( :activities => { :status => "Out", user_id: current_user.id } ).count
0
votes

Have you tried with a join?

Activity.joins(:student)
        .where(status: "Out", user_id: current_user.id)
        .where(student: { gender: "male" })
        .count