user3809888
user3809888

Reputation: 407

Rails: How to structure a user model/controller to handle saving to favorites?

I am building a Rails app that has data about the US Congress. Each legislator has their own page. I want users of my app to be able to add specific legislators to their favorites. I have created a Legislator resource as well as a User resource in my app. I also have a Favorites model for a has_many through association.

The User model looks like this:

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

I have not implemented the "add legislator to favorites" feature yet. Right now the User update/edit page is only used for updating user information.

My question is how to design/structure this feature. Should I add a method to the User model to add/remove legislators from favorites, and modify the update method in the User controller to handle adding/removing favorites? Or should I be using the Favorites controller instead?

I have a couple ideas on how to do this, but I'm not sure what would be the cleanest/RESTful way.

Upvotes: 0

Views: 68

Answers (1)

joshua.paling
joshua.paling

Reputation: 13952

Use the Favourites controller. When a user favourites a legislator, they are 'creating' a favourite record. And when they un-favourite a legistlator, they are 'destroying' a favourite record.

So, you probably won't need update at all. Use favourites#create and favourites#destroy. This is the rest-ful way.

As for putting the logic in your Model vs Controller, for something that simple I'd personally just put it in the controller.

Upvotes: 1

Related Questions