dcangulo
dcangulo

Reputation: 2107

Association command using has_many :through associations in Ruby on Rails

I have a has_many :through association.

#app/user.rb
class User < ApplicationRecord
  has_many :members
  has_many :projects, :through => :members
end

#app/project.rb
class Project < ApplicationRecord
  has_many :members
  has_many :users, :through => :members
end

#app/member.rb
class Member < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

I have the database schema as follows:

create_table "members", force: :cascade do |t|
  t.integer "user_id"
  t.integer "project_id"
  t.integer "is_owner"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["project_id"], name: "index_members_on_project_id"
  t.index ["user_id"], name: "index_members_on_user_id"
end

create_table "projects", force: :cascade do |t|
  t.string "name"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "users", force: :cascade do |t|
  t.string "first_name"
  t.string "last_name"
  t.string "email"
  t.string "password_digest"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

I can get Member ID, User_ID, Project_ID, and is_owner when I use the command @project.members

I can get user_id, first_name, last_name, email, and password when I use the command @project.users

What command should I use to get member_id, first_name, last_name?

I can get what I want using the SQL query SELECT * FROM members INNER JOIN users ON users.id = members.user_id but I don't want to use raw SQL.

Can someone tell me how to convert that query into a Ruby on rails command?

Upvotes: 1

Views: 113

Answers (1)

Sandeep Garg
Sandeep Garg

Reputation: 1276

You can get your desired result using following code

Member.joins(:user)

It will generate the same query what you are specifying in your question i.e.

SELECT * FROM members INNER JOIN users ON users.id = members.user_id

Upvotes: 1

Related Questions