【问题标题】:Rails: "new or edit" path helper?Rails:“新建或编辑”路径助手?
【发布时间】:2011-08-03 06:39:15
【问题描述】:

是否有一种简单直接的方法可以在视图中提供链接以在资源不存在时创建资源或在资源存在时编辑现有资源?

IE:

User has_one :profile

目前我会做类似...

-if current_user.profile?
  = link_to 'Edit Profile', edit_profile_path(current_user.profile)
-else
  = link_to 'Create Profile', new_profile_path

如果这是唯一的方法,这没关系,但我一直在尝试看看是否有“Rails Way”来做类似的事情:

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

有什么好干净的方法来做这样的事情吗?类似于Model.find_or_create_by_attribute(....) 的视图

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 new-operator edit link-to


    【解决方案1】:

    编写一个助手来封装逻辑中更复杂的部分,然后你的视图就可以干净了。

    # 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)
    

    【讨论】:

    • 那行得通。我想自己创建一个助手有点明显......并且会解释为什么似乎没有类似的内置函数。谢谢!
    【解决方案2】:

    我也遇到了同样的问题,但我想为很多模型做这件事。必须为每个人编写一个新的助手似乎很乏味,所以我想出了这个:

    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_or_edit_path :child

    【讨论】:

    • @parent com 来自哪里?
    【解决方案3】:

    另一种方式!

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

    【讨论】:

      【解决方案4】:

      如果你想要一个通用的方式:

      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 %>
      

      【讨论】:

        【解决方案5】:

        试试这个:

        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) %>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-11
          • 1970-01-01
          • 2013-09-28
          • 1970-01-01
          • 1970-01-01
          • 2019-01-24
          相关资源
          最近更新 更多