3

I am pretty new to rails and am attempting to have two partial form_for buttons which switch back and forth on click via ajax replaceWith.

My goal is to have a follow button which when clicked switches to "unfollow", and switches the underlying button action as well. The first switch works great (and I can see in the database it went through), but when I click the newly made "unfollow" button the same idea (to switch to "follow") doesn't occur, instead it prints the text of my .js.erb file (however I can see the unfollow action gets committed to the database). Basically on the second click the correct rendering does not occur, and I'm very unsure why.

I'll post some code below, and sorry if this isn't a good question, I'm having some trouble understanding a lot of the Ajax methods.

Thank you so much! Lisa

_unfollow.html.erb

<%= form_for(@user,:remote => true,method: :delete, format: 'js') do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large", id: "Submit"%>
<% end %>

_follow.html.erb

<%= form_for(@user, :remote=>true,      format: 'js') do |f| %>
<%= f.submit "Follow", class: "btn btn-large btn-primary", id: "Submit" %>
<% end %>

The create/destroy called by the controller (I would like them to switch between the two partials above)

create.js.erb

$('#Submit').replaceWith("<%= escape_javascript(raw render :partial => 'follow' )%>");

destroy.js.erb

$('#Submit').replaceWith("<%= escape_javascript(render( :partial => 'unfollow')) %>");

Again, no matter which partial/form I have on the page initially, the first click correctly switches, and the second takes the .js.erb and prints it out the page (with the html inserted)

4

2 に答える 2

1

次のように、送信ボタンだけでなく、フォーム全体を置き換えてみてください。

_unfollow.html.erb

<%= form_for(@user,:remote => true,method: :delete, format: 'js', html: { id: "button-form" }) do |f| %>
  <%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>

_follow.html.erb

<%= form_for(@user, :remote=>true, format: 'js', html: { id: "button-form" }) do |f| %>
  <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>

create.js.erb

$('#button-form').replaceWith("<%= escape_javascript(render :partial => 'follow' )%>");

destroy.js.erb

$('#button-form').replaceWith("<%= escape_javascript(render( :partial => 'unfollow')) %>");
于 2013-01-12T01:15:17.523 に答える
0

rawcreate.js.erbで呼び出しを削除してみてください。

于 2013-01-12T00:29:18.177 に答える