助手中的动态路径 [英] Dynamic Paths in Helper

查看:167
本文介绍了助手中的动态路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为管理员链接创建一个帮助程序。在不同的
视图中,我有代码

 <%if current_user%> 
<%= link_to编辑,edit_model_path(model)%>
<%= link_toNew,new_model_path%>
<%= link_to删除,model,:confirm => 你是一个Noob,方法
=> :删除%>
<%end%>

只有在登录时才显示这些。



我想在他们的地方做这样的事情

 <%= admin_links(model)%> 

并将当前项目传递到应用程序帮助程序


$ b $如果current_user
a =#{link_toeditedit_m_path(m)}
a #{link_tonewnew_m_path}
a<< #{link_to删除,m,:confirm =>你的Noob,:方法
=>:delete}
end
end

或类似的东西。

解决方案

基本上你需要将模型的类名转换成指向正确路径的东西。

  model_name = m.class.to_s.underscore 

然后使用它来调用相应的路径方法

  link_toedit,send(edit_# {model_name} _path,m)

除此之外,您不需要将link_tos在#{} 中,因为该函数只返回一个字符串。


I'm trying to create a helper method for my admin links. In quite a few views I have the code

<% if current_user %>
<%= link_to "Edit", edit_model_path(model) %>
<%= link_to "New", new_model_path %>
<%= link_to "Delete", model, :confirm => "You're a Noob",  :method
=> :delete %>
<% end %>

that only display these when logged in.

I would like to do something like this in their place

<%= admin_links(model) %>

and pass the current item into the application helper method

def admin_links(m)
 if current_user
  a = "#{link_to "edit" edit_m_path(m)}"
  a << "#{link_to "new" new_m_path}"
  a << "#{link_to "Delete", m, :confirm => "Your a Noob",  :method
=> :delete}"
 end
end

Or something of the like.

解决方案

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.

这篇关于助手中的动态路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆