I'm trying to write a helper method that accepts the name of a plural resource and returns a corresponding link. The essence of the method is:
我正在尝试编写一个helper方法,它接受复数资源的名称并返回相应的链接。该方法的本质是:
def get_link(resource)
link_to "#{resource.capitalize}", resource_path
end
—Clearly the resource_path
part above doesn't work. What I'd like is to be able to pass foos
to get foos_path
and bars
to get bars_path
etc. How can I do that? I can't quite work out the syntax.
-显然,上面的resource_path部分不能工作。我想要的是能够通过foos来获取foos_path和bar来获取bars_path等等。我怎么做呢?我不太懂语法。
3 个解决方案
#1
7
def get_link(resource)
link_to "#{resource.capitalize}", send("#{resource}_path")
end
#2
2
def get_link(resource) link_to(resource.to_s.titleize, send("#{resource}_path")) end
The to_s call on resource is to support passing symbols as resource. So
对资源的to_s调用是支持将符号作为资源传递。所以
get_link("foos")
will work and also
工作,也
get_link(:foos)
#3
0
If you want to construct a RESTful route with a member:
如果您想与成员一起构建一个RESTful路由:
send("edit_#{resource}_path".to_sym, @resource)
#1
7
def get_link(resource)
link_to "#{resource.capitalize}", send("#{resource}_path")
end
#2
2
def get_link(resource) link_to(resource.to_s.titleize, send("#{resource}_path")) end
The to_s call on resource is to support passing symbols as resource. So
对资源的to_s调用是支持将符号作为资源传递。所以
get_link("foos")
will work and also
工作,也
get_link(:foos)
#3
0
If you want to construct a RESTful route with a member:
如果您想与成员一起构建一个RESTful路由:
send("edit_#{resource}_path".to_sym, @resource)