显示记录计数 - Ruby on Rails - Ajax

时间:2009-11-19 21:04:09

标签: ruby-on-rails ruby ajax count

我是铁杆的新手很抱歉,如果有时候我没有多大意义。这是我想要做的。我正在努力建立一个投票系统。因此,在博客文章旁边有一个说“投票”的链接(可能会在稍后说)。到目前为止,我已经工作了:当点击投票按钮时,值“1”被传递到投票表,然后通过AJAX(我复制了评论功能)在投票下方显示特定的帖子投票记录。我想让它渲染更新的计数,而不是渲染下面的所有数字'1'。

我的投票表中有成功输入的'投票'和'post_id'列。我的想法是我可以改变我的部分模板来做到这一点。这是代码:

votes_controller:

class VotesController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    @vote = @post.votes.create!(params[:vote])

    respond_to do |format|
       format.html { redirect_to @post}
       format.js
     end
  end
end

  def count
    @post = Post.find(params[:post_id])
    @vote = calculate :count

      respond_to do |format|
         format.html { redirect_to @post}
         format.js
    end
  end
end

以下是显示的页面/posts/show.html.erb:

<div id="backto"<%= link_to 'Back to all BattleCries', posts_path %></div>
<%= render :partial => @post %><br/>


<p5>Add a Comment</p5>
<div id="belt">
    <div id="belttext">
<% remote_form_for [@post, Comment.new] do |f| %>
    <p>
        <%= f.text_area ( :body, :class => "commentarea") %>
    </p>
    <%= f.submit "Add Comment"%>
<% end %>
</div>
<div id="beltbottom">
</div>
</div><br/>
<br/><p5>Comment Stream </p5> 
<div id="comments">
    <%= render :partial => @post.comments %>

</div>

<p>
<% remote_form_for [@post, Vote.new] do |f| %>
    <p>

        <%= f.hidden_field :vote, :value => '1' %>
    </p>
    <%= f.submit "Vote" %>
<% end %>
<div id="vote">
<div id="votes">
    <%= render :partial => @post.votes %>
</div>
</div>
</p>

这是:partial,/ quote / _vote.html.erb :(这是我认为我只需将其更改为vote.count,或post.count或其他但无法使其工作的地方)。

<% div_for vote do %>

        <%= h(vote.vote) %> 
    <% end %>

这是/votes/create.js.rjs文件:

page.insert_html :bottom, :votes, :partial => @vote
page[@vote].visual_effect :highlight

我希望一切都有道理。

3 个答案:

答案 0 :(得分:2)

你可能想要:

<%= @post.votes.count %>

答案 1 :(得分:2)

我认为这是重复的,因为你的.rjs是“插入底部”而不是“替换”...你可能想要page.replace_html

最好有一个包含帖子投票数量的DIV或SPAN标签...然后让你的.rjs文件用投票数更新DIV的inner_html(这将是@ post.votes。伯爵... ...我认为你真的不需要偏袒。

答案 2 :(得分:1)

您可能也想使用replace而不是insert_html - 这有意义吗? Insert只是向DOM添加更多元素,而replace将替换元素。

相关问题