user1436111
user1436111

Reputation: 2141

How to create a row in an intermediate relationship in Ruby on Rails

I have tables Users, Locations and Follows, where Users have_many locations :through => :follows. Follows belongs_to both users and locations. I want to add a row into the Follows table--that is, create a Following relationship between a user and a location.

I'm not sure how to do this, or if I'm implementing Follows right:

class CreateFollows < ActiveRecord::Migration
   def change
     create_table :follows |do| t
      t.references :user_id
      t.references :location_id
      t.timestamps
     end
   end
end

And the code I'm trying to use to add a Follows relationship, given userid and locationid, is

newFollow = Follow.new(:user_id => userid, :location_id => locationid)
newFollow.save

I'm getting the error unknown attribute: user_id.

any ideas? I'm really stuck. Thanks so much!

Upvotes: 1

Views: 115

Answers (1)

user229044
user229044

Reputation: 239311

In a migration, references expects the field name without the _id, and it then appends _id to it. Right now, you're creating two columns: user_id_id and location_id_id.

Instead of these lines...

t.references :user_id
t.references :location_id

... you need these lines:

t.references :user
t.references :location

And once you've fixed your column names...

You don't have to manually create records in then "through" table. If you have a user, and you have a location, and your associations are setup correctly (has_many follows; has_many :locations, through: :follows), you can simply use

user.locations << location

This will automatically create the joining record.

Upvotes: 4

Related Questions