Dynamic Paths in Helper

大兔子大兔子 提交于 2019-12-02 17:33:33

basically you need to transform the class name of the model into something pointing to the correct path.

model_name = m.class.to_s.underscore

And then use it to call the appropriate path methods

link_to "edit", send("edit_#{model_name}_path", m)

As an aside, you don't need to put the link_tos in #{} because that function simply returns a string.

Rails provides polymorphic routes to handle this problem: http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html

= link_to "Edit", polymorphic_path(model), :method => :put

I would use a partial for this - instead of a helper. Wherever you want to display these links in your views, simply render the partial:

<%= render :partial => "admin_links", :locals => { :model => model } %>

In _admin_links.html.erb just paste the original code:

<% if current_user %>
  <%= link_to "Edit", edit_model_path(model) %>
  <%= link_to "New", new_model_path %>
  <%= link_to "Delete", model, :confirm => "Your a Noob", :method => :delete %>
<% end %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!