And*_*rew 9 ruby-on-rails edit new-operator link-to ruby-on-rails-3
是否有一种简单直接的方法可以在视图中提供链接,以便在资源不存在时创建资源,如果存在,则编辑现有资源?
IE:
User has_one :profile
Run Code Online (Sandbox Code Playgroud)
目前我会做的事......
-if current_user.profile?
= link_to 'Edit Profile', edit_profile_path(current_user.profile)
-else
= link_to 'Create Profile', new_profile_path
Run Code Online (Sandbox Code Playgroud)
这是好的,如果这是唯一的方法,但我一直在试图看看是否有一个"Rails方式"来做类似的事情:
= link_to 'Manage Profile', new_or_edit_path(current_user.profile)
Run Code Online (Sandbox Code Playgroud)
有没有什么好干净的方法来做那样的事情?类似于视图的东西Model.find_or_create_by_attribute(....)
Dou*_*rer 28
编写一个帮助程序来封装逻辑中更复杂的部分,然后您的视图就可以清理.
# profile_helper.rb
module ProfileHelper
def new_or_edit_profile_path(profile)
profile ? edit_profile_path(profile) : new_profile_path(profile)
end
end
Run Code Online (Sandbox Code Playgroud)
现在在你的意见中:
link_to 'Manage Profile', new_or_edit_profile_path(current_user.profile)
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,但有很多我想做的模型.为每个人写一个新助手似乎很乏味,所以我想出了这个:
def new_or_edit_path(model_type)
if @parent.send(model_type)
send("edit_#{model_type.to_s}_path", @parent.send(model_type))
else
send("new_#{model_type.to_s}_path", :parent_id => @parent.id)
end
end
Run Code Online (Sandbox Code Playgroud)
然后,您可以调用new_or_edit_path :child父模型的任何子项.
其他方式!
<%=
link_to_if(current_user.profile?, "Edit Profile",edit_profile_path(current_user.profile)) do
link_to('Create Profile', new_profile_path)
end
%>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30436 次 |
| 最近记录: |