gpt4 book ai didi

ruby-on-rails - rails : Allow users to upvote only once a pin

转载 作者:数据小太阳 更新时间:2023-10-29 08:15:48 25 4
gpt4 key购买 nike

我的 Rails 应用程序中有一个点赞系统,允许用户点赞 Pin 图。但我想限制一个 Pin 只能投票一次的能力。

app/controllers/pins_controller.rb

  def upvote
@pin = Pin.find(params[:id])
@pin.votes.create
redirect_to(pins_path)
end

app/models/pin.rb

class Pin < ActiveRecord::Base

belongs_to :user

has_many :votes, dependent: :destroy

has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" }

end

app/config/routes.rb

  resources :pins do
member do
post 'upvote'
end
end

我不确定如何实现它,因为我试图实现一个只允许用户投票一次的系统,这不是我想要的,我希望他们只能对“PIN”投票一次。我知道 acts_as_votable gem 提供此功能,但由于我没有使用它,所以我想知道是否有一种方法可以在我自己的代码中实现它。

有什么想法吗?

更新:此方法每个图钉只允许投一票。查看@Ege 解决方案

让它与这个一起工作:

def upvote
@pin = Pin.find(params[:id])

if @pin.votes.count == 0
@pin.votes.create
redirect_to(pins_path)
else flash[:notice] = "You have already upvote this!"
redirect_to(pins_path)
end
end

最佳答案

您选择了 beautifulcoder 的答案作为正确答案,但您应该意识到它可能不正确,如果您是 Rails 的新手,它可能并不明显。

您说一个 Pin 图应该只有一票,但大概您的意思是它应该每个用户有一票,例如,每个用户应该只能给一个 Pin 图点赞一次。这就是投票机制通常的工作方式。

根据 beautifulcoder 的回答,如果我给一个 Pin 投票,你将无法给它投票,因为你的 Controller 会计算 Pin 上的票数,返回 1(因为我给它投票)并阻止你给它投票。此外,它会闪烁一条消息说你已经投票了,而你还没有!

如何解决这个问题?幸运的是,Rails 使这变得 super 简单。你的投票实际上是一个变相的加入模型。它在用户和 pin 之间建立关系(即关联)。用户可以对 pin 进行投票,用户也可以对 pin 进行投票。换句话说,投票“连接”用户和引脚!您需要做的是利用 ActiveRecord Associations 来定义这种关系。 .

您的 Pin 图模型将添加此关联:

class Pin < ActiveRecord::Base

has_many :votes, dependent: :destroy
has_many :upvoted_users, through: :votes, source: :user

...

end

这允许您执行诸如 @pin.upvoted_users 之类的操作,并获取对该 pin 投赞成票的用户列表。如果您希望能够通知 pin 所有者,那就太好了!

您还想向您的用户模型添加反向关联:

class User < ActiveRecord::Base

has_many :votes, dependent: :destroy
has_many :upvoted_pins, through: :votes, source: :pin

...

end

然后像这样更改投票模型:

class Vote < ActiveRecord::Base

belongs_to :user
belongs_to :pin
validates_uniqueness_of :pin_id, scope: :user_id

end

最后在你的 Controller 中,你会做:

def upvote
@pin = Pin.find(params[:id])

if @pin.votes.create(user_id: current_user.id)
flash[:notice] = "Thank you for upvoting!"
redirect_to(pins_path)
else
flash[:notice] = "You have already upvoted this!"
redirect_to(pins_path)
end
end

瞧!您现在有了一个解决方案,用户可以在其中为项目投票,但每个项目只能投票一次。

关于ruby-on-rails - rails : Allow users to upvote only once a pin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24596651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com