【发布时间】:2014-07-08 11:22:34
【问题描述】:
我有一个带有基本设置的 rails 应用程序,允许用户对 pin 进行投票,这些 pin 的顺序是从最多投票到较少投票。我现在想做的是呈现用户在其个人资料上点赞的 pin 列表。
这是我的配置:
app/controllers/pins_controllers.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
app/models/pin.rb
class Pin < ActiveRecord::Base
belongs_to :user
has_many :votes, dependent: :destroy
has_many :upvoted_users, through: :votes, source: :user
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
app/models/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
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
还有我的 routes.rb
resources :pins do
member do
post 'upvote'
end
end
你有什么想法吗?
【问题讨论】:
-
你想查询得到用户投票的pin列表吗?
-
@lcicle 是的,然后我希望用户投票赞成的图钉显示在他的个人资料中。你明白我的意思吗?
标签: ruby-on-rails ruby devise