Question: Rails join on user column

Question

Rails join on user column

Answers 1
Added at 2016-12-26 19:12
Tags
Question

I'm trying to get all Activities related to users of the same school (a string on the user object), but the error I'm getting is this:

Can't join 'Activity' to association named 'users'; perhaps you misspelled it?

activity_controller.rb

@school = current_user.school
@bathroom = Activity.includes(:users).where(name: 'Bathroom').where( :user => { :school => @school} )

and 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 "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "name"
    t.string   "grade"
    t.string   "school"
    t.integer  "maxout"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end
Answers
nr: #1 dodano: 2016-12-26 19:12

Not users but user because Activity belongs to User

@bathroom = Activity.includes(:user).where(name: 'Bathroom').where( :users => { :school => @school} )

But User has many activities so User.includes(:activities)

Of course, you have to provide associations:

class Activity
  belongs_to :user

class User
  has_many :activities
Source Show
◀ Wstecz