Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 铁轨:;“新建或编辑”;路径助手?_Ruby On Rails_Ruby On Rails 3_New Operator_Edit_Link To - Fatal编程技术网

Ruby on rails 铁轨:;“新建或编辑”;路径助手?

Ruby on rails 铁轨:;“新建或编辑”;路径助手?,ruby-on-rails,ruby-on-rails-3,new-operator,edit,link-to,Ruby On Rails,Ruby On Rails 3,New Operator,Edit,Link To,是否有一种简单而直接的方法在视图中提供链接,如果资源不存在,则创建该资源;如果存在,则编辑现有资源 即: 现在我会做一些像 -if current_user.profile? = link_to 'Edit Profile', edit_profile_path(current_user.profile) -else = link_to 'Create Profile', new_profile_path 如果这是唯一的方法,这也没关系,但我一直在尝试看看是否有一种“Rails方式”来

是否有一种简单而直接的方法在视图中提供链接,如果资源不存在,则创建该资源;如果存在,则编辑现有资源

即:

现在我会做一些像

-if current_user.profile?
  = link_to 'Edit Profile', edit_profile_path(current_user.profile)
-else
  = link_to 'Create Profile', new_profile_path
如果这是唯一的方法,这也没关系,但我一直在尝试看看是否有一种“Rails方式”来执行以下操作:

= link_to 'Manage Profile', new_or_edit_path(current_user.profile)

有没有什么好的干净的方法来做这样的事情?类似于
模型的视图等价物。通过属性(..)查找或创建
编写一个帮助程序来封装逻辑中更复杂的部分,这样您的视图就可以干净了

# profile_helper.rb
module ProfileHelper

  def new_or_edit_profile_path(profile)
    profile ? edit_profile_path(profile) : new_profile_path(profile)
  end

end
现在在你看来:

link_to 'Manage Profile', new_or_edit_profile_path(current_user.profile)
另一条路

  <%=
     link_to_if(current_user.profile?, "Edit Profile",edit_profile_path(current_user.profile)) do
       link_to('Create Profile', new_profile_path)
     end
  %>

我也遇到了同样的问题,但有很多型号我都想这样做。为每个人编写一个新的助手似乎很乏味,因此我提出了以下建议:

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
然后,您可以为父模型的任何子模型调用
new\u或\u edit\u path:child

尝试以下操作:

module ProfilesHelper

  def new_or_edit_profile_path(profile)
    profile ? edit_profile_path(profile) : new_profile_path(profile)
  end

end
还有你的链接,比如:

<%= link_to 'Manage Profile', new_or_edit_profile_path(@user.profile) %>

如果需要通用方法:

def new_or_edit_path(model)
  model.new_record? ? send("new_#{model.model_name.singular}_path", model) : send("edit_#{model.model_name.singular}_path", model)
end
其中,
model
是视图中的实例变量。例如:

# new.html.erb from users
<%= link_to new_or_edit_path(@user) do %>Clear Form<% end %>
#来自用户的new.html.erb
清晰的形式

这很有效。我想自己创建一个助手是很明显的。。。并解释了为什么没有类似的内置功能。谢谢@parent com来自哪里?
# new.html.erb from users
<%= link_to new_or_edit_path(@user) do %>Clear Form<% end %>