Quoc Nguyen
Quoc Nguyen

Reputation: 9

Add to favorites ( multiple model )

I'm a new to rails but I have a big problem with my app.

Business Logic - User can favorite restaurants, menus, items. We have :

class Restaurant < ActiveRecord::Base
     has_many :items, :dependent=>:destroy
     has_many :menus, :dependent=> :destroy
     belongs_to :owner, :class_name => 'User'
end
class Menu < ActiveRecord::Base
     belongs_to :restaurant
     has_many :items,:dependent=>:destroy
end
class Item < ActiveRecord::Base
     belongs_to :restaurant
     belongs_to :menu
end
class User < ActiveRecord::Base
     has_many :restaurants
end

Could someone help me resolve my problem ?

Thanks for your support

p/s: Sorry for my english, i'm vietnamese.

Upvotes: 1

Views: 413

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

You need to build a polymorphic association between a User and a Favoritable item. This is done using polymorphic association bellow:

class Restaurant < ActiveRecord::Base
  belongs_to :favoritable, polymorphic: true
end

class Menu < ActiveRecord::Base
  belongs_to :favoritable, polymorphic: true
end

class Item < ActiveRecord::Base
  belongs_to :favoritable, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :favorites, as: :favoritable
end

Then you can retrieve user's favorites with the following:

user = User.first
user.favorites
# => [...]

You can build a new favorite using:

user.favorites.build(favorite_params)

Or you can assign a favoritable object directly using:

user.favorites << Restaurant.find(1)
user.favorites << Menu.find(1)
user.favorites << Item.find(1)

More information about polymorphic associations.

Upvotes: 3

Related Questions