在我的 Rails 3 项目中,我有一个这样的路由列表:
resources :projects do
resources :studies
end
resources :sticky_notes
resources :study_templates
...
目前默认情况下,可以使用 params[:id] 调用这些路由的 URL 中的 id,但我希望能够使用 params[:sticky_note_id]、params[:study_template_id]、params[:study_id] 调用它们], 等等。有没有办法为这些项目的ID指定参数名称?我是否必须在没有“资源”的情况下手动写出每条路线?
谢谢!
编辑:这是我正在尝试做的一个例子: 当路由如上定义时会发生这种情况:
resources :projects do
resources :studies
end
# results in /projects/:project_id/studies/:id
# /projects/:project_id/studies/:id/edit
# /projects/:project_id/studies/:id/new
# etc.
resources :sticky_notes
# results in /sticky_notes/:id
# /sticky_notes/:id/edit
# /sticky_notes/:id/new
# etc.
这就是我想要的:
match '/projects/:project_id/studies/:study_id' => 'studies#show'
match '/projects/:project_id/studies/:study_id/edit' => 'studies#edit'
match '/projects/:project_id/studies/:study_id/new' => 'studies#new'
...
# results in /projects/:project_id/studies/:study_id
# /projects/:project_id/studies/:study_id/edit
# etc
match '/sticky_notes/:sticky_note_id' => 'sticky_notes#show'
match '/sticky_notes/:sticky_note_id/edit' => 'sticky_notes#edit'
match '/sticky_notes/:sticky_note_id/new' => 'sticky_notes#new'
...
# results in /sticky_notes/:sticky_note_id
# /sticky_notes/:sticky_note_id/edit
# etc
我想要第二部分,但没有对我已经很大的路线文件进行所有工作。 :) 这可能吗?
最佳答案
毕竟“routes.rb”只是一个简单的 ruby 文件,那么为什么不使用 ruby 代码,甚至可以创建一个方法来生成必要的路由..让我们看一个使用资源数组的简单示例,如果您想使用嵌套资源,您可能需要修改方法以使用散列链,以便传递您想要添加成员的资源:
def add_nested_resource(toadd=nil, controller=nil, resources=[])
return if toadd.nil? || controller.nil? || ressources.empty?
resources.each { |x|
resources x do
resources toadd, :controller => controller
end
}
end
add_nested_resource(:notes, "notes", [:resource1, :resource2, ..., :resourceX]
相当于
resources :resource1 do
resources :notes, :controller => "notes"
end
resources :resource2 do
resources :notes, :controller => "notes"
end
.
.
.
resources :resourceX do
resources :notes, :controller => "notes"
end
这样你就可以轻松地编写很多路由。 在 notes_controller 中,当然你可能必须区分哪个资源调用了它,我通常在相应的表单中添加一个隐藏字段,我在其中留下嵌套嵌套对象的对象的“分类”名称......就像
<%= form_for ... someform for resource1... do |f| %>
...
<%= hidden_field_tag :nesting_object, "Resource1" %>
...
<% end %>
希望这能帮助你度过难关...
关于ruby-on-rails - 如何更改 Rails 3 路由中的默认参数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392595/