简体   繁体   中英

Click for controller action (remote: true) and then update href

I can't get a rails link_to to update its href after the original link is clicked and followed, with remote => true . Instead, it updates the href and then follows the new route. I tried setTimeout (commented out), but this doesn't seem to help.

.html.erb (ignore most divs, it's just a link_to with styles)

<%= link_to onboarding_favorite_path(:param => f.id), class: "onboarding-favorite", remote: true do %>
  <div style="display:inline-block;float:left" class="onboard-not-chosen">
    <span style="display:none;" class="food_id"><%=f.id%></span>
    <div style="display:inline-block;float:left" class="hovereffect">
      <img class="img-responsive" src=<%=f.image%>>
      <div class="overlay">
        <h2><%=f.name%></h2>
      </div>
    </div>
  </div>
<% end %>

.coffee (ignore from the click up to the line beginning in param , which fetches the unique part of the new route)

$('.onboard-not-chosen').click ->
  $(this).removeClass('onboard-not-chosen').addClass('onboard-chosen')
  $(this).find(".hovereffect").addClass("hovereffect-chosen").removeClass("hovereffect")
  $(this).find(".img-responsive").addClass("img-responsive-chosen").removeClass("img-responsive")
  $(this).find(".overlay").addClass("overlay-chosen").removeClass("overlay")
  param = $(this).find(".food_id").html()
  new_href = "/undo_onboarding_favorite?param=" + param
  original_href = $(this).parent().parent().find(".onboarding-favorite").attr("href")
 #setTimeout ( ->
  $(this).parent().parent().find(".onboarding-favorite").attr("href",new_href)
 #), 1000

I'm trying to allow users to select foods that they like. Upon selecting a food, the link should change so that the food can be unselected (in case of accidental selection or mind-changing). The routes ( onboarding_favorite and undo_onboarding_favorite ) should be followed remotely to update the database, and then the user should see an update via jQuery.

In the past, I've managed this by just having two separate buttons that get hidden and unhidden as necessary, but I think updating the href is a much better approach.

if you're using jquery-ujs (which is needed to work with remote: true ) the solution would be the following:

$(document).on "ajax:success", ".onboard-favorite", (e, data, status, xhr) ->
  # do your stuff..

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