wrburgess wrburgess - 6 months ago 10
Ruby Question

Adding attribute values to a join table record in a has_many :through association upon creation

I am setting up a has_many :through relationship on my Rails 3.2 app. I have most everything working, except that I'm not sure how to add values to attributes on the join table when relationships are created.

Here are the models (notice the source_id on the Checkins table):

create_table "users", :force => true do |t|
t.integer "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

create_table "checkins", :force => true do |t|
t.integer "user_id"
t.integer "location_id"
t.integer "source_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

create_table "locations", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end


Here's the relationship setup:

class User < ActiveRecord::Base
has_many :checkins
has_many :locations, :through => :checkins
end

class Location < ActiveRecord::Base
has_many :checkins
has_many :users, :through => :checkins
end

class Checkin < ActiveRecord::Base
belongs_to :location
belongs_to :user
end


I'm using these instructions (in essence) to loadi a User and Location and create the relationship with a Checkin:

source_id = 10
@user = User.first
@location = Location.first
@user.locations << @location


So, my question is, how do I also add a source_id value to the Checkins table when using this line:

@user.locations << @location


I'm also open to suggestions on a better process for creating new User Checkins with this relationship than what I have above (I've seen the create and build methods used, but none seemed to work for me)

Answer

Create a Checkin object directly.

checkin = Checkin.new user: @user, location: @location, source_id: source_id 
checkin.save
Comments