简体   繁体   中英

Rails link_to with ajax remote true not updating view

I have this little app that has events. In my index view for events I iterate through all events and display some data. In inside the each loop I have a link to 'Upvote' a particular event, this is an ajax request. For some reasons my view wont update right away but update when I clicked 'Upvote' again.

Here is my link to 'Upvote'

<div id="upvote_link_<%= event.id%>">
   <%= link_to('Upvote', upvote_event_path(event), method: :post, remote: true)%>
</div>

This is my upvote method where I increment the votes field.

  def upvote
    @event = Event.find(params[:id])
    Event.increment_counter(:votes, @event.id)
    respond_to do |format|
      format.js
    end 
  end

Next is my upvote.js.erb where I replaced the old votes value with the new value.

$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event )%>");

Next is my _upvote.html.erb partial that replaces the old votes value.

<span style="font-family:MetaSerifOT-Book;font-size:13px;">
    <%= pluralize(event.votes, "vote") %>
</span>

The problem is when I clicked the 'Upvote' link my request goes through and the votes field in my Event model gets updated but the view wont update until I clicked Upvote again. I am not sure what is going on. Any ideas or suggestions?

Update This is where I set up the id: upvotes_<%= event.id %> I have isolated the Votes count inside a partial.

    <div id="upvotes_<%= event.id%>">
            <%= render 'upvote', event: event %>
    </div>

The problem is in controller code. The @event object is not getting reloaded, I think. One solution is you have to reload the @event object either in the view like

$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event.reload )%>"); .

To add to Santanu 's answer, you'll want to look at your method's code:

 #app/controllers/events_controller.rb
 class EventsController < ApplicationController
    respond_to :js, only: :upvote #-> if you have the responders gem

    def upvote
       @event = Event.find params[:id]
       @event.increment! :votes
       respond_with @event
    end
  end

increment!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM