在我的rails应用程序中,我有一个upvote系统,它允许人们upvote pin。然后,当用户对引脚进行投票时,我会在用户配置文件中呈现一个upvoted引脚列表。我想知道的是提供一个赞成特定图钉的用户列表。
应用程序/控制器/ pins_controller.rb
def upvote
@pin = Pin.find(params[:id])
if @pin.votes.create(user_id: current_user.id)
flash[:notice] = "Thank you for upvoting! You can upvote a startup only once."
redirect_to(pins_path)
else
flash[:notice] = "You have already upvoted this!"
redirect_to(pins_path)
end
end
应用程序/控制器/ users_controller.rb
def show
@user = User.find(params[:id])
@pins_for_user = []
@user.votes.each do |vote|
@pins_for_user << vote.pin
end
end
应用程序/模型/ pin.rb
class Pin < ActiveRecord::Base
belongs_to :user
has_many :votes, dependent: :destroy
has_many :upvoted_users, through: :votes, source: :user
has_many :rewards, dependent: :destroy
has_many :rewarded_users, through: :rewards, source: :user
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
应用程序/模型/ user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins
has_many :votes, dependent: :destroy
has_many :upvoted_pins, through: :votes, source: :pin
has_many :rewards, dependent: :destroy
has_many :rewarded_pins, through: :rewards, source: :pin
end
app / models / vote.rb
class Vote < ActiveRecord::Base
belongs_to :user
belongs_to :pin, counter_cache: true
validates_uniqueness_of :pin_id, scope: :user_id
end
我在考虑使用@ pin.upvoted_users来提供这个列表,但我没有成功地实现它,任何想法?