Rails : has_many (through) Association : Assign values or make complex queries

To be continue..

Lets consider an entity relationship as following where there could be many to many or one to many relationship through a join table as described below.

class User < ActiveRecord::Base
  has_many :roles, through: :assignments
end
# Note:
# Role table has predefined roles users can have
#   Example:
#      id: 1, name: 'recruiter'
#      id: 2, name: 'manager'
#   Roles are mapped to the users via `Assignments` table
class Role < ActiveRecord::Base
  has_many :users, through: :assignments
end

# == Schema Information
#
# Table name: roles
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime
# updated_at :datetime
# value :integer
# title :string(255)
class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

# == Schema Information
#
# Table name: assignments
#
# id :integer not null, primary key
# user_id :integer
# role_id :integer
# created_at :datetime
# updated_at :datetime

Creating / Updating records

# The user has multiple roles viz: `recruiter` and `manager`
User.create(role_ids: [1, 2], first_name: 'John', last_name: 'Smith')

Querying via Join table

# Querying to find all the users whose role is 3 ( supervisor ) 
User.joins(:assignments).where(assignments: {role_id: [3]})

Some helpful links:

http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html

http://blog.arkency.com/2013/12/rails4-preloading/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s