0

在我的应用程序中,我有项目,这些项目可以使用make_flaggable gem 标记为“最喜欢的”。

我想创建一个页面,每个用户都可以看到他最喜欢的项目。

任何帮助我都会非常感激!

项目.rb

make_flaggable :favorite

用户.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
4

1 回答 1

2

make_flaggable gem 生成一个链接flaggablesflaggers以下模式的数据库表:

flaggings
  flaggable (polymorphic)
  flagger (polymorphic)
  reason
  timestamps

以及对应的型号:

class MakeFlaggable::Flagging < ActiveRecord::Base
  belongs_to :flaggable, :polymorphic => true
  belongs_to :flagger, :polymorphic => true
end

当您调用make_flaggableandmake_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
于 2013-04-23T18:24:01.943 回答