如何在Rails中更简洁地生成此自定义URL?

时间:2011-07-17 23:07:33

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

我在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])

2 个答案:

答案 0 :(得分:4)

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

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)

代码中的其他地方。

答案 1 :(得分:0)

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