在我的应用程序中,我有项目,并且可以使用make_flaggable gem将这些项目标记为“收藏”。
我想创建一个页面,每个用户都可以看到自己喜欢的项目。
任何帮助都非常感谢!
item.rb的
make_flaggable :favorite
user.rb
make_flagger
items_controller.rb
def favorite
@current_user = User.first
@item = Item.find(params[:id])
@current_user.flag(@item, :favorite)
redirect_to @item, :notice => "Added to Your Favorites"
end
def unfavorite
@current_user = User.first
@item = Item.find(params[:id])
@current_user.unflag(@item, :favorite)
redirect_to @item, :notice => "Removed from Your Favorites"
end
答案 0 :(得分:2)
make_flaggable gem生成一个数据库表,使用以下模式将flaggables
链接到flaggers
:
flaggings
flaggable (polymorphic)
flagger (polymorphic)
reason
timestamps
以及相应的模型:
class MakeFlaggable::Flagging < ActiveRecord::Base
belongs_to :flaggable, :polymorphic => true
belongs_to :flagger, :polymorphic => true
end
当您致电make_flaggable
和make_flagger
时,您的用户和项目会添加以下关系:
class Item < ActiveRecord::Base
has_many :flaggings, :class_name => "MakeFlaggable::Flagging", :as => :flaggable
end
class User < ActiveRecord::Base
has_many :flaggings, :class_name => "MakeFlaggable::Flagging", :as => :flagger
end
所以,我们希望通过关系User -> Flagging -> Flaggable
。不幸的是,由于flaggable
关系是多态的,我们不能只是添加到用户:
has_many :flagables, through: :flaggings
但是,由于您只标记项目,因此可以显式设置源类型:
class User < ActiveRecord::Base
has_many :flagged_items, :through => :flaggings, :source => :flaggable, :source_type => 'Item'
end
现在你可以有一个控制器方法,如:
@current_user = User.first
@items = @current_user.flagged_items