2

我正在尝试实施一个投票系统,其中投票受选民 ip_address 限制。

我有一个 post 模型,它有 many_votes 并且投票属于 post 模型。

我的问题是如何以及在哪里定义“current_user”以及如何在视图中实现它。

目前我正在创建这样的投票:

<%= link_to(post_votes_path(post), :method => 'post') do %>
<%= song.votes.size %>

工作正常,除了任何人都可以投票,我想阻止它。请我不是在寻找宝石,我只是想从头开始学习此功能。

干杯。

这是我的帖子控制器代码:

def create
@post = Post.new(params[:post])

respond_to do |format|
  if @post.save
    format.html { redirect_to root_url, notice: 'Post was successfully created.' }
  else
    format.html { render action: "new" }
  end
end
end

并为创建操作投票控制器代码:

def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create
respond_to do |format|
  format.html { redirect_to root_url }
  #format.js 
end
end
4

2 回答 2

1

投票表需要在ip具有唯一验证约束的列中。然后,如果您尝试为每个 ip 记录多个投票,则控制器的保存将失败,您可以检测并使用它来显示错误。您必须发布您的控制器代码以获得更好的答案。

于 2013-07-04T20:36:18.393 回答
1

就像 MrYoshiji 建议的那样,您应该在您的投票表中添加一个 voter_ip 列。

您可以将此 ARwhere条款添加到您的帖子/投票控制器

if @post.votes.where(voter_ip: request.remote_ip).empty?
  @post.votes.create(vote: params[:post_vote])
end

这将检查该帖子是否有来自当前 ip 的任何投票。如果没有投票记录,则添加一个新的投票,其参数值为post_vote

如果您希望向vote模型添加约束,则需要进行范围验证。

validates_uniqueness_of :voter_ip, scope: :post_id

使用范围参数时,唯一性约束应用于 和 的组合,voter_ippost_id不是voter_ip单独使用。

于 2013-07-04T21:31:45.153 回答