我创建了一个黑客新闻克隆,我试图实现一个投票系统,该系统根据过去7天的排名从大多数投票到最少投票。我知道有几个宝石可以做到这一点,但我想在使用宝石之前手动做一次。如何在没有投票权的情况下在Rails中实现投票
我有第一个问题,是多票。我希望让每个用户都能够根据自己的意愿对尽可能多的链接进行投票,但每个链接只能投一票。我试图在我的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.rb
由users
,links
和votes
在两个links
和votes
一个user_id
属性为这里列出:
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>
你可以为它创建自定义的验证。 –