如何在没有投票gem的情况下在Rails中实现投票

时间:2013-10-08 19:08:09

标签: ruby postgresql ruby-on-rails-4 voting voting-system

我创建了一个黑客新闻克隆,并且我正在尝试实施一个投票系统,根据过去7天的排名从最多投票到最少投票。我知道有几个宝石可以做到这一点,但我想在使用宝石之前手动完成一次。

我有第一个问题,是多票。我希望每个用户都可以根据需要对尽可能多的链接进行投票,但每个链接的限制为一票。我试图在我的votes_controller中实现这一点,但它只允许链接本身共有一票,而不是每个链接有一票的用户。这是votes_controller中的方法:

 def create
    @vote = Vote.new(voter_params)
    if @vote.save
      redirect_to links_path, notice: "Thanks for voting!"
    else
      redirect_to links_path, notice: "Sorry, you can only vote on a link once."  
    end
  end

我的schema.rbuserslinksvotes组成,user_idlinks都有votes个属性如下所列:

 create_table "links", force: true do |t|
    t.string   "description"
    t.string   "url"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.string   "user_name"
    t.string   "password_digest"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "votes", force: true do |t|
    t.integer  "user_id"
    t.integer  "link_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

如何重构我当前的操作以允许对任何链接进行投票,但每个用户只能投票一次?

好的,我的第二个也是最后一个问题是,一旦我把投票问题摆平了,我怎样才能根据过去7天的选票从最多投票到最少投票,当然要通过postgres服务器方式。在我看来,通过数据库更有效率。我很感激我能得到的任何见解,我感到非常难过,谢谢!!

这是我的链接模型,以提供更好的主意:

class Link < ActiveRecord::Base
  validates :url, :presence => true, :url => true
  belongs_to :user
  has_many :votes
  has_many :comments, :as => :commentable

  def self.sort_by_votes
    sorted_votes = Link.all.sort_by { |link| link.votes.count }
    sorted_votes.reverse
  end
end

这是我的观点:

<% if current_user %>
<p style="float:right; padding-right: 10px;"> Logged in as: <%= current_user.name %> </p>
<% end %>
<div class="container" id="content">
  <button class="btn btn-default btn-xs" style="float:right"><%= link_to "New Link", new_link_path %></button><br><br>
<table >
  <thead>
    <tr>
    </tr>
  </thead>
  <tbody class="stories">
    <% @links.sort_by_votes.each do |link| %>
          <%= form_for link.votes.new do |f| %>
                   <%= f.hidden_field :link_id %>
                   <%= f.submit '▲' %>
                   <% end %>
          <%= "#{link.votes.count} votes " %>
          <%= link_to link.description, link.url %>
          <small><%= "(#{link.url})" %></small>
          <span class="date"><%= link.created_at.to_time.strftime("%b %-d, %Y @ %-I:%M%P") %></span>
          <br>
          <button class="btn btn-default btn-xs">
            <%= link_to "Delete", link, :method => :delete, :data => { :confirm => "are you sure about that?" } %>
          </button>
          <button class="btn btn-default btn-xs">
            <%= link_to "Comment", link_path(link)%>
          </button><hr/>
      <% end %>
</tbody>

</div>

1 个答案:

答案 0 :(得分:4)

您应该使用验证:

class Vote
  #...
  validates :user_id, uniqueness: { scope: :link_id }

关系计数器相当复杂,具体取决于您的数据库,并且通常会产生复杂的耗时查询。我使用counter_cache选项。关于如何使用它们有一个nice post

$ rails g migration add_votes_counter_to_link votes_count:integer
class AddVotesCounterToLinks < ActiveRecord::Migration
  def change
    add_column :links, :votes_count, :integer, default: 0
  end
end
$ rake db:migrate

class Vote
  belongs_to :link, counter_cache: true
end

class Link
  has_many :votes

  scope :most_voted, -> do
    where(created_at: (Time.now - 7.days)..Time.now ) # created 7 days ago
    .order('votes_count DESC')                        # ordered by votes_count
    .limit(100)                                       # first 100
  end

然后你可以做以下事情:

Link.most_voted