Showing posts with label namespace. Show all posts
Showing posts with label namespace. Show all posts

Friday, October 5, 2012

Rails Namespace, Nested Resource and form_for

Couple days ago, I ran into a problem when I try to use namespace, nested resources and form_for in Rails 3 and ruby 1.9.3. I try to setup some thing similar to this, a namespace :admin, with nested resources :menus, and :menu_items. Here is the routes.rb:
namespace :admin do
  resources :menus do
    resources :menu_items
  end
end
I think it's probably common used case. Unfortunately, I got this error when I try to create a new MenuItem in menu_items/_form.html.erb
undefind method 'admin_menu_items_path' for #<#<Class ...
...
 1: <%= form_for(@admin_menu_item)do |f| %>
      ...
17: end
I realize that the standard scaffolding won't work for me, so I start googling. Right away, I get a lot of hits. It's seem to be a common issue. However, the solutions create quite a confusion for me. I try different solutions, some looking good but don't work! .. Here is what I find working.

 First, in admin/menu_items_controller.rb, method 'new':
def new 
  @menu = Admin::Menu.find(params[:menu_id])
  @menu_item = @menu.menu_items.build
  ...
end
It load up the @menu, and build @menu_item, nothing surprise me. I also get rid of than "admin" prefix. It's simpler that way.