user3809888
user3809888

Reputation: 407

Adding a favorites association to a user model in Rails

I am working on a Rails test app that has data on bills and legislators from the US Congress.

I have a (site) User model and a Legislator model. I want to allow users to add individual legislators to their favorites. Right now I have the following models (unnecessary bits omitted):

class User < ActiveRecord::Base
  has_many :favorites
  has_many :legislators, through: :favorites
end

class Legislator < ActiveRecord::Base
  has_many :bills
  has_many :favorites
  has_many :users, through: :favorites
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :legislator
end

I am trying to figure out if this is the correct way to set up these associations. In the Rails console, if I try to do:

User.first.favorites.create(legislator_id: 123)

Then the favorite is created, but the user_id field for this newly created favorite is nil:

=> #<Favorite id: 5, user_id: nil, legislator_id: 145, ... >

I want the user_id to be automatically assigned to the User on which .favorites.create is called so that I do not have to do

User.first.favorites.create(legislator_id: 123, user_id: User.first.id).  

What do I have to modify to get this to work?

Upvotes: 2

Views: 172

Answers (2)

Nic Nilov
Nic Nilov

Reputation: 5155

What you're doing is a many-to-many relationship between User and Legislator through Favorites. You don't need to create Favorites objects explicitly as Rails handles that.

legislator = Legislator.first
User.first.legislators << legislator

This will create necessary Favorite entry. Note that by default uniqueness of Favorites is not checked so there can be many entries reflecting the relationship between the same user and legislator. To handle that add this to Favorite model:

validates_uniqueness_of :user_id, :scope => :legislator_id

Upvotes: 3

Redrick
Redrick

Reputation: 466

Hi so what you are doing seems really similar to this case and I think solves your problem, have a look HERE in this question

Upvotes: -1

Related Questions