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.
答案 0 :(得分:1)
如果您使用jquery-ujs
(需要使用remote: true
)
解决方案如下:
$(document).on "ajax:success", ".onboard-favorite", (e, data, status, xhr) ->
# do your stuff..