简单的投票系统,没有宝石--如何跟踪向上或向下投票,并允许每个用户_id投一票。

问题描述 投票:1回答:1

任何帮助将是非常感激的。我的铁轨之旅还不到三周,因此提前道歉。

我写了一个简单的列表投票系统,用户可以向上或向下投票。它的工作还不错。但是,我卡在两个问题上。

  1. 什么是最有效的方法来限制用户投票一次?但是,他们就可以向上或向下切换投票。我开始过度设计一个 after_touch 回调。最好的做法是在User模型中设置一个has_one :vote吗?之后的一切都由Active Record来处理吗?
  2. 是否可以在用户点击投票按钮时,禁用该按钮(向上或向下)。而不需要再增加一个数据库列来跟踪上票或下票?这样他们就可以在向上或向下投票之间进行切换,在最初的投票之后。

投票控制器

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] } %>

先谢谢你。

ruby-on-rails cancancan
1个回答
0
投票

这很让人困惑。你说你想设置 Userhas_one :vote. 但你的表似乎是一个连接表,用于连接 user_idlist_id. 因此,一个人可以有一个投票每列表,正确的?你可以强制执行唯一性,但不是你提到的那种方式。

你没有所有模型的模型代码,但是你可以让一个List模型有

has_many :votes
has_many :users, through: :votes

那么用户有

has_many :votes
has_many :lists, through: votes

和投票模型可以有

belongs_to: :user
belongs_to: :list
validates :user_id, :uniqueness => { :scope => :list_id }

最后一个唯一性验证,从我这里了解的情况来看,可以防止每个列表有超过一个用户投票。http:/api.rubyonrails.orgclassesActiveRecordValidationsClassMethods.html#method-i-validates_uniqueness_of-----。

© www.soinside.com 2019 - 2024. All rights reserved.