Rails Ajax Render Partial (voting system)

帅比萌擦擦* 提交于 2019-12-08 09:16:54

问题


I am having trouble re-rendering a partial through an Ajax request. I can currently pass other things through the js file such as alert() and even changing the html in the current div. But when I try and render the partial (rating, in this instance), nothing will refresh. The partials work fine in the sense that they render on pagination and on load, but not after I click an upvote or downvote. I'm using nested partials so that it renders _tracks first, then _rating. Here's what I have..what am I missing?

vote.js.erb

$(".rating").html("<%= escape_javascript(render(:partial => 'rating')) %>")

With this I also these, with no success.

   $(".rating").html("<%= escape_javascript(render("rating")) %>")
   $(".rating").html("<%= escape_javascript( render( :partial => "rating", :locals => { :track => track }) ) %>")

This, on the other hand, does work:

$(".rating").html("<%= escape_javascript("test text here) %>")

_tracks.html.erb

    <% for track in @tracks %>
            <div class="span4">
                <div class="track">
                    <div class="rating">
                        <%= render :partial => "rating", :locals => { :track => track } %>
                    </div>

                    <a href="<%= track.youtube_link %>"></a>

                    <% if current_user.admin? %> 
                        <%= link_to "delete", track, method: :delete, confirm: "You sure?" %>
                        <%= link_to "edit", edit_track_path(track) %>
                    <% end %>
                </div>
            </div>
<% end %>

_rating.html.erb

<% vt = track.votetype(current_user) %>

                <% if vt != "up" %>
                    <%= link_to image_tag("up_arrow.png", alt: "Upvote"), vote_path(track, :type => "up"), :remote => true %>
                <% elsif %>
                    <%= "up" %>
                <% end %>

                <%= track.rating %>

                <% if vt != "down" %>
                    <%= link_to image_tag("down_arrow.png", alt: "Downvote"), vote_path(track, :type => "down"), :remote => true %>
                <% elsif %>
                    <%= "down" %>
                <% end %>

track controller

@vote.update_attributes(:vote_type => params[:type])
        if @vote.save
      respond_to do |format|
        format.html {redirect_to :back}
        format.js
      end

回答1:


$(".rating").html("<%= escape_javascript( render( :partial => "rating", :locals => { :track => track }) ) %>")

needs to be

$(".rating").html("<%= escape_javascript( render( :partial => "rating", :locals => { :track => @track }) ) %>")

The @ symbol passes the variable through, unlike the for loop in the previous partial where you didn't need it. Working fine now.



来源:https://stackoverflow.com/questions/11654021/rails-ajax-render-partial-voting-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!