控制器命名空间和路由问题

时间:2010-12-23 08:41:18

标签: ruby-on-rails routing

我使用一个型号'User'创建了一个路由测试rails3 app:

rails new routing_test_app
rails generate model User name:string
rails generate scaffold_controller admin/user
rake db:migrate

添加到routes.db:

namespace :admin do
  resources :users
end

rake routes

admin_users GET    /admin/users(.:format)          {:action=>"index", :controller=>"admin/users"}
admin_users POST   /admin/users(.:format)          {:action=>"create", :controller=>"admin/users"}
new_admin_user GET    /admin/users/new(.:format)      {:action=>"new", :controller=>"admin/users"}
edit_admin_user GET    /admin/users/:id/edit(.:format) {:action=>"edit", :controller=>"admin/users"}
admin_user GET    /admin/users/:id(.:format)      {:action=>"show", :controller=>"admin/users"}
admin_user PUT    /admin/users/:id(.:format)      {:action=>"update", :controller=>"admin/users"}
admin_user DELETE /admin/users/:id(.:format)      {:action=>"destroy", :controller=>"admin/users"}

视图/管理/用户/ _form.html.erb

<%= form_for(@admin_user) do |f| %>
  <% if @admin_user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@admin_user.errors.count, "error") %> prohibited this admin_user from being saved:</h2>

      <ul>
      <% @admin_user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
    <%= f.text_field :name %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

当我去'http:// localhost:3000 / admin / users / new'trail引发错误时:

undefined method `users_path' for #<#<Class:0x0000010116ca90>:0x000001011588d8>

提取的来源(第1行):

1: <%= form_for(@admin_user) do |f| %>
2:   <% if @admin_user.errors.any? %>
3:     <div id="error_explanation">
4:       <h2><%= pluralize(@admin_user.errors.count, "error") %> prohibited this admin_user from being saved:</h2>

2 个答案:

答案 0 :(得分:5)

那是因为@admin_userUser对象,所以Rails猜测URL帮助器是users_path。这是一个简单的修复。只需将@admin_user form_for param替换为[:admin, @admin_user]即可。您可能还希望重命名实例变量@user以减少重复次数。必须使用数组是使用命名空间的一个缺点,因此应该始终考虑到这一点。

答案 1 :(得分:4)

form_for方法不会猜测嵌套路由。试试这个:

form_for [:admin, @admin_user] do |f|