我在Rails中有这个帮助函数,我想知道user_path
可以以某种方式从@user
派生出来,它作为参数传递给函数。眼下,user_path
在我的功能被硬编码是不漂亮:如何从Rails助手函数中的对象派生路径?
def link_to_next(entry)
link_to ">>", user_path(entry.next)
end
这是我如何使用辅助函数:
<%= link_to_next(@user) %>
感谢您的帮助!
我在Rails中有这个帮助函数,我想知道user_path
可以以某种方式从@user
派生出来,它作为参数传递给函数。眼下,user_path
在我的功能被硬编码是不漂亮:如何从Rails助手函数中的对象派生路径?
def link_to_next(entry)
link_to ">>", user_path(entry.next)
end
这是我如何使用辅助函数:
<%= link_to_next(@user) %>
感谢您的帮助!
你可以使用用来定义Rails的3.2.13的form_for
方法,该方法ActiveModel::Naming.param_key
:
@foo = User.new
# => #<User id: nil, email: nil>
ActiveModel::Naming.param_key(@foo)
# => "user"
现在,您可以定义link_to_next
这样的:
def link_to_next(entry)
next_entry = entry.next
path_method = "#{ActiveModel::Naming.param_key(next_entry)}_path"
link_to('>>', send(path_method, next_entry))
end
这很好,非常感谢! – Tintin81
嗨,我可以问一下,你是如何得出这些知识的?你研究过这个问题吗,还是你对Rails的内部很熟悉? –
<%= url_for( @user)%> –
我想迈克尔的意思是'url_for(entry.next)'。比下面的解决方案清洁得多。 –