加入收藏夹(多种型号)

时间:2013-10-22 13:03:05

标签: ruby-on-rails ruby database ruby-on-rails-3

我是rails的新手,但我的应用程序存在很大问题。

业务逻辑    - 用户可以收藏餐厅,菜单,商品。 我们有:

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

有人可以帮我解决问题吗?

感谢您的支持

p / s :对不起我的英语,我是越南人。

1 个答案:

答案 0 :(得分:3)

您需要在UserFavoritable项之间建立多态关联。这是使用下面的polymorphic关联完成的:

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

然后您可以使用以下内容检索用户的收藏夹:

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

您可以使用以下方式构建新收藏夹:

user.favorites.build(favorite_params)

或者您可以使用以下方式直接指定一个可收藏的对象:

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

有关polymorphic associations的更多信息。