您没有提及您正在使用的 javascript 库。这个解决方案是基于 jquery 的。只需一个操作destroy 即可轻松完成您想做的事情。但我会建议一种不同的技术来解决它。我发现 rjs 很受限制。去 jquery taconite 插件。它的所有标记,而不是......一堆 erb 混合的 javascript 不太吸引人的眼睛!
所以现在您将拥有destroy.xml.erb 而不是您的destroy.rjs。在我进入您需要添加的内容之前,让我们看看您需要为您的 destroy 操作进行哪些修改。
之前:
def destroy
@model = Model.find(params[:id])
@model.destroy
respond_to do |format|
format.html { redirect_to :action => :index }
format.xml
end
end
之后:
def destroy
@model = Model.find(params[:id])
@model.destroy
@template = params[:template]
respond_to do |format|
format.html { redirect_to :action => :index }
format.xml
end
end
在你的 routes.rb 中添加一个命名路由来简化事情:
map.destroy_using_template 'destroy/:id/:template', :controller => "controller", :action => "destroy"
在你看来:
将 jquery taconite 插件添加到 <layout>.html.erb 的标题中,
<%= javascript_include_tag "jquery.js", "jquery.taconite.js" %>
在模板 1 的视图中:
假设你使用链接删除。
<%= link_to "Delete", destroy_using_template_path(:id => "1", :template => "temp1"), :method => :delete, :confirm => "Are you sure you want to delete the record?" %>
模板 2 也是如此:
假设你使用链接删除。
<%= link_to "Delete", destroy_using_template_path(:id => "1", :template => "temp2"), :method => :delete, :confirm => "Are you sure you want to delete the record?" %>
现在在你的destroy.xml.erb
<taconite>
<% if @template=="temp1" %>
<remove select="#template1" />
<% elsif @template=="temp2" %>
<remove select="#template2" />
<% end %>
<eval>
//OPTIONAL: Execute some javascript here if you want. You can do most of the DOM modifications using taconite itself.
alert("HEY!!!");
</eval>
</taconite>
现在不容易吗? :)
请记住,在使用 taconite 时,您必须确保 destroy.xml.erb 中的代码符合 XML。确保关闭所有打开的标签。在此处阅读有关铁燧岩的更多信息:http://malsup.com/jquery/taconite/
Taconite 在标记中实现了所有常规的 jquery DOM 修饰符以及它自己的一些额外修饰符。如果您想切换到 javascript,只需在 eval 标记中包含该 javascript,即可轻松实现,如上所示。