在ajax帖子之后更新rails button_to的最简单方法是什么?

时间:2012-05-20 18:34:15

标签: ruby-on-rails ruby-on-rails-3 jquery ujs

我有两个button_to调用来播放视频。该按钮在我的视频控制器中调用一个特色动作。

在我的控制器中

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

在我看来

<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>

成功的ajax帖子后,将按钮更改为“删除”的最不显眼的方法是什么?其他一切都正常。我尝试在features.js.erb文件中进行jQuery切换调用,但它不起作用。

1 个答案:

答案 0 :(得分:1)

我喜欢这样做:

<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]) %>");

是的,我认为这不是最好的方法。我希望看到一个更正确的解决方案。

编辑: 对于循环,该解决方案不适合。第二个版本:

<% 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 %>

在一些咖啡文件中:

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

我不确定这个代码(它显然需要重构),但我希望你能得到这个想法。