Kyle C
Kyle C

Reputation: 4097

What is the easiest way to update a rails button_to after an ajax post?

I have two button_to calls to feature a video. The button calls a featured action in my video controller.

In my controller

def featured
 video = Video.find(params[:id]) 
 video.nfeatured = params[:nfeatured]
 video.save
respond_to do |format|
  format.html { redirect_to :back }
  format.js
 end
end

In my view

<td class="featured">
<% if video.nfeatured == false %>
<%= button_to 'Feature', featured_network_video_path(network, video, 
:nfeatured => true), :remote => true, :class => :feature %>

 <% else %>
 <%= button_to 'Remove', featured_network_video_path(network, video,
 :nfeatured => false), :remote => true, :class => :unfeature  %>
<% end %>
</td>

What is the most unobtrusive way to change the button to 'Remove' after a successful ajax post? Everything else is working properly. I tried make a jQuery toggle call in a featured.js.erb file but it did not work.

Upvotes: 0

Views: 1249

Answers (1)

Mik
Mik

Reputation: 4187

I like to do so:

<td class="featured">
<%= render :template => "videos/featured" %>
</td>

featured.html.erb:

<% if @video.nfeatured == false %>
  <%= button_to 'Feature', featured_network_video_path(@network, @video, 
  :nfeatured => true), :remote => true, :class => :feature %>

<% else %>
  <%= button_to 'Remove', featured_network_video_path(@network, @video,
  :nfeatured => false), :remote => true, :class => :unfeature  %>
<% end %>

featured.js.erb

$(".featured").html("<%= j(render :template => "videos/featured", :handlers => [:erb]) %>");

And yes, I think this is not the best way. I would like to see a more right solution.

edited: For a loop this solution is not suitable. The second version:

<% unless video.nfeatured %>
  <%= button_to 'Feature', featured_network_video_path(network, video, 
  :nfeatured => true), :remote => true, :class => :feature %>
  <%= button_to 'Remove', featured_network_video_path(network, video,
  :nfeatured => false), :remote => true, :class => 'unfeature hidden'  %>
<% else %>
  <%= button_to 'Feature', featured_network_video_path(network, video, 
  :nfeatured => true), :remote => true, :class => 'feature hidden' %>
  <%= button_to 'Remove', featured_network_video_path(network, video,
  :nfeatured => false), :remote => true, :class => :unfeature  %>
<% end %>

in some a coffee file:

$('.featured').bind "ajax:success", ->
  $(this).toggle()
  $(this).closest('a').toggle()

I'm not sure about this code (it obviously needs refactor), but I hope you get the idea.

Upvotes: 1

Related Questions