【问题标题】:How can I generate this custom URL more succinctly in Rails?如何在 Rails 中更简洁地生成此自定义 URL?
【发布时间】:2011-07-17 23:07:33
【问题描述】:
  • 我在 Rails 3 中设置了以下路线

get '/:user_id/wants/:id' => 'wanted_items#public_view', :as => 'public_wanted_item'

  • 在 Rake Routes 中提供以下内容:
public_wanted_item GET    /:user_id/wants/:id(.:format) {:controller=>"wanted_items", :action=>"public_view"}
  • 它会生成以下 URL,这正是我想要的:

/username/wants/itemname

问题是,为了在我的视图中生成它,我必须使用一个非常详细的构造,我在其中明确指定 :user_id:id

ruby-1.9.2-p0 :012 > app.public_wanted_item_path(:user_id => item.user, :id => item)

有什么方法可以让这个调用更简洁,因为我会在我的应用程序中大量使用它?

谢谢


编辑:我找到了一个可行的解决方案..粘贴在下面

如果我使用以下构造,它似乎也能正常工作,这正是我所希望的......虽然我不确定它究竟为什么工作......

ruby-1.9.2-p0 :002 > app.public_wanted_item_path item.user, item

因为下一个不行,反而报错:

ruby-1.9.2-p0 :004 > app.public_wanted_item_path([item.user, item])

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routing


    【解决方案1】:

    这听起来像是应用程序助手的工作。您可以添加如下内容:

    def item_path_for(item)
        app.public_wanted_item_path(:user_id => item.user, :id => item)
    end
    

    到你的app/helpers/application_helper.rb 然后你就可以使用

    <%= item_path_for(pancakes) %>
    

    在您的观点(或 HAML 等价物)或

    include ApplicationHelper
    #...
    path = item_path_for(pancakes)
    

    代码中的其他地方。

    【讨论】:

      【解决方案2】:
      app.public_wanted_item_path(:user_id => item.user.id, :id => item.id)
      

      【讨论】:

      • 谢谢..但这实际上比我已经拥有的更冗长...?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2022-01-13
      • 2011-08-28
      相关资源
      最近更新 更多