2012-05-20 49 views
0

我有两个button_to调用功能的视频。该按钮在我的视频控制器中调用特色动作。在ajax文章之后更新rails 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后“删除”最不显眼的方式?其他一切正常。我试着在一个featured.js.erb文件中做一个jQuery切换调用,但它不起作用。

回答

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

我不知道这个代码(这显然需要重构),但我希望你的想法。

+1

为什么不使用'j'而不是'escape_javascript'?前者是不是更容易记住? – jdoe

+0

非常感谢您的回答......我在回调中收到500个服务器错误。它成功保存了该操作,但没有正确呈现视图。有什么想法吗?我也必须传入局部变量,因为这个渲染是在一个块内。 –

+0

@jdoe,谢谢,我以前不知道)@Kyle C,对不起,我忘了你必须传递本地参数,或者使用实例变量。我更喜欢第二种解决方案。你有一个错误可能是因为你没有在'featured'动作中定义变量'@ network'和'@ video'。查看更多日志错误,它有很大帮助。我编辑了答案。 –

相关问题