Showing Number of Entries - Ruby on Rails - Ajax

I am new to rails, so I'm sorry if sometimes I don't make any sense. Here is what I am trying to do. I am trying to create a voting system. So, next to the blog post there is a link that says β€œvoice” (probably this will be said later). I still work: when the vote button is pressed, the value "1" is delivered to the voting table, and then the records of specific entries at the table are displayed under the voting via AJAX (I copied the comment functionality). Instead of displaying the entire number "1" below, I want it to display an updated counter.

My voting table contains the columns "vote" and "post_id" which are successfully entered. I thought I could just change my partial template to do this. Here is the code:

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

Here is the page where /posts/show.html.erb is displayed:

<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>

Here: partial, / votes / _vote.html.erb: (this is where I thought I would just need to change it to vote.count or post.count or something else, but can't make it work).

<% div_for vote do %>

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

Here is the /votes/create.js.rjs file:

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

I hope everything makes sense.

+3
source share
3 answers

I think it repeats because your .rjs "inserts below" div instead of "replace" ... you probably want page.replace_html

DIV SPAN, ... .rjs DIV inner_html ( @post.votes. count)... , .

+2

, :

<%= @post.votes.count %>
+2

You might also want to use replace instead of insert_html - does that make sense? An insert is simply adding more elements to the DOM, while replacing will replace the element.

+1
source

Source: https://habr.com/ru/post/1723409/


All Articles