我有这些模型
发布has_many投票和投票belongs_to问题。投票模型有一个布尔投票属性。在“问题”索引视图中,我希望循环处理问题,并显示标题、正文、向上投票按钮、向下投票按钮以及显示当前存在多少向上和向下票数的相应标签。我使用带有隐藏字段的表单(1或0)进行issue_id和表决。问题模型上的方法应该用来统计选票。但我一直得到0的回报。在服务器日志中,我看到了用正确的issue_id和投票值创建的选票,但是由于某些原因,查询无法工作。
问题模型
class Issue < ActiveRecord::Base
attr_accessible :body, :end_at, :title
validates_presence_of :title, :body, :end_at
has_many :votes
def upvotes_count
votes.count(:conditions => "vote = 1")
end
def downvotes_count
votes.count(:conditions => "vote = 0")
end
def totalvotes_count
votes.count
end
endindex.html.erb
<% @issues.each do |issue| %>
<li>
<div class="issue">
<h2><%= issue.title %></h2>
<p><%= issue.body %></p>
<%= form_for(@vote, :remote => true) do |f| %>
<%= f.hidden_field "issue_id", :value => issue.id %>
<%= f.hidden_field "vote", :value => 1 %>
<%= submit_tag issue.upvotes_count.to_s + " Up", :class => 'up-vote' %>
<% end %>
<%= form_for(@vote, :remote => true) do |f| %>
<%= f.hidden_field "issue_id", :value => issue.id %>
<%= f.hidden_field "vote", :value => 0 %>
<%= submit_tag issue.downvotes_count.to_s + " Down", :class => 'down-vote' %>
<% end %>
</div>
</li>
<% end %>选票控制器
class VotesController < ApplicationController
def index
@votes = Vote.find(:all, :include => :issue)
end
def new
@vote = Vote.new(params[:vote])
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @vote }
end
end
def create
@vote = Vote.new(params[:vote])
respond_to do |format|
if @vote.save
format.js
format.html { redirect_to issues_path }
else
format.html { redirect_to issues_path }
end
end
end
end发布控制器(部分)
class IssuesController < ApplicationController
# GET /issues
# GET /issues.json
def index
@issues = Issue.all
@vote = Vote.new
respond_to do |format|
format.html # index.html.erb
format.json { render json: @issues }
end结束
发布于 2012-10-01 20:34:42
我相信您的问题是您没有在模型中调用"self“,但是正如tamersalama所提到的,对于简单的投票跟踪来说,这可能是过分的。在:upvote和:downvote属性上编写一个简单的+1方法可能是最简单的。
发布于 2012-10-01 20:22:14
vote的默认值是什么。如果它是空的-那就不起作用了。
更仔细地阅读这个问题--它看起来像是vote中的值,决定它是向上还是否决。我建议您为Vote使用STI (单表继承)机制,在该机制中,您将创建一个类型列来存储投票类型(要么是:up表决,要么是下发),并在type属性上设置索引。
然而,所有这些似乎都是过度的(取决于您域的其他部分)。您可以简单地将选票与每一个问题一起缓存。一栏投上票,另一栏投反对票就足够了。除非你想跟踪选票上的其他属性(比如那些投票的人)。
https://stackoverflow.com/questions/12680437
复制相似问题