我有这些模型
- 问题
- 投票
发行 has_many votes 和 Vote belongs_to issue。Vote 模型有一个布尔投票属性。在问题索引视图中,我想循环浏览问题并显示标题、正文、赞成票按钮、反对票按钮以及显示当前有多少赞成票和反对票的相应标签。我使用带有隐藏字段的表单来执行此操作,用于 issue_id 和投票(1 或 0)。问题模型上的方法应该计算选票。但我不断得到 0 返回。Totalvotes_count 有效,但其他两个无效。在服务器日志中,我看到使用正确的 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
end
index.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
结尾