![](/img/trans.png)
[英]Simple voting system doesn't add vote to database after clicking vote up/down (Rails)?
[英]Simple voting system without a gem - how to track up or down vote and allow one vote per user_id
非常感激任何的帮助。 我的铁路之旅还不到三周,因此提前道歉。
我写了一个简单的列表投票系统,用户可以对列表进行投票。 它工作正常。 但是,我被困在两个问题上:
after_touch
回调。 在用户 model 中设置 has_one:vote 的最佳做法是什么? Active Record 会处理之后的所有事情吗?投票 Controller
class VotesController < ApplicationController
def vote_up
@list = List.find(params[:list_id])
@vote = Vote.find_or_create_by(list_id: params[:id], user_id: current_user.id)
Vote.increment_counter(:vote_count, @vote)
redirect_to list_path(@list), notice: 'Voted Up.'
end
def vote_down
@list = List.find(params[:list_id])
@vote = Vote.find_or_create_by(list_id: params[:id], user_id: current_user.id)
Vote.decrement_counter(:vote_count, @vote)
redirect_to list_path(@list), notice: 'Voted Down.'
end
end
图式
create_table "votes", force: :cascade do |t|
t.integer "vote_count"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.bigint "list_id", null: false
t.integer "user_id"
t.index ["list_id"], name: "index_votes_on_list_id"
end
show.html.erb 的摘录,带有相关的上/下投票按钮
<% if @list.votes.any? %>
Count Of Votes <%= content_tag(:p, list_vote_counter?) %>
<% end %>
<%= button_to 'Vote Up', list_vote_up_path, method: :post, params: { list_id: params[:id] } %>
<%= button_to 'Vote Down', list_vote_down_path, method: :post, params: { list_id: params[:id] } %>
先感谢您。
这令人困惑。 你说你想将User
设置为has_one:vote
。 但是您的表似乎是user_id
和list_id
的连接表。 所以一个人可以在每个列表中投一票,对吗? 您可以强制执行唯一性,但不能按照您提到的方式执行。
您没有所有型号的 model 代码,但您可以列出 model 有
has_many :votes
has_many :users, through: :votes
然后用户有
has_many :votes
has_many :lists, through: votes
和投票 model 可以有
belongs_to: :user
belongs_to: :list
validates :user_id, :uniqueness => { :scope => :list_id }
根据我在这里的理解,最后的唯一性验证将阻止每个列表的多个用户投票: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.