您没有提及您正在使用的 javascript 库。这个解决方案是基于 jquery 的。只需一个动作就可以很容易地做你想做的事destroy
。但我会建议一种不同的技术来解决它。我发现 rjs 很受限制。去 jquery taconite 插件。它的所有标记,而不是......一堆与 erb 混合的 javascript 不太吸引人的眼睛!
因此,现在destroy.rjs
您将拥有一个destroy.xml.erb
. 在我进入您需要添加的内容之前,让我们看看您需要为您的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,即可轻松完成,如上所示。