问题描述
|
假设
post = Post.first
,我可以写一个链接
link_to \"First Post\",post # I guess Rails here understand to which model the
# object \"post\" belongs
但是要编辑帖子,链接是
link_to \"Edit First Post\",edit_post_path(post)
是否可以编写类似以下内容的内容:
link_to \"Edit First Post\",post,:type => :edit
这样就不必指定对象属于哪个模型?那不是DRYer吗?
解决方法
您可以使用
method
和action
代替type
请参阅说明文件
例:
link_to \"Profile\",:controller => \"profiles\",:action => \"show\",:id => @profile
# => <a href=\"/profiles/show/1\">Profile</a>
, 这是我实施的可能解决方案。在application_helper.rb
中添加方法:
def edit_path(item,other = {})
send(\"edit_#{item.class.to_s.downcase}_path\",item,other)
end
现在,我可以使用以下内容创建编辑链接:
link_to \"Edit Post\",edit_path(post)
link_to \"Edit User\",edit_path(user)
代替
link_to \"Edit Post\",edit_post_path(post)
link_to \"Edit User\",edit_user_path(user)
我觉得这是DRYer,但也许只是我。