【问题标题】:About default routing helpers, is there some redundancy?关于默认路由助手,是否有一些冗余?
【发布时间】:2011-05-27 21:03:08
【问题描述】:

假设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吗?

【问题讨论】:

    标签: ruby-on-rails resources routing helper


    【解决方案1】:

    您可以使用methodaction 代替type

    documentation

    例子:

    link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
    # => <a href="/profiles/show/1">Profile</a>
    

    【讨论】:

    • 你是对的。但我想知道是否有可能只使用两种类型的数据(对象、链接类型)使 rails 生成编辑链接,在您的示例中,您给出了三个(控制器、操作、对象 ID)。
    • 你可以试试link_to "Edit", post, :action =&gt; :edit 吗?我无法从我所在的位置对其进行测试,但我认为它可能会起作用。
    • 阅读routing guide,我不确定您是否可以添加更多内容。 edit_post_path(:id) 似乎是正确的做法。
    【解决方案2】:

    这是我实施的一个可能的解决方案。在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,但也许只有我一个人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2013-03-22
      • 1970-01-01
      • 2012-08-05
      • 2015-03-14
      相关资源
      最近更新 更多