How to avoid Rails scaffold to place model into namespace

Rails 4 generators are a bit different. If you use the scaffold_controller generator it will pre-build all the view files, but by default it will look for a model called Admin::Portfolio. To load the correct model just pass the model name as an argument to the generator.

$ rails g model Portfolio
      invoke  active_record
      create    db/migrate/20150822164921_create_portfolios.rb
      create    app/models/portfolio.rb
      invoke    test_unit
      create      test/models/portfolio_test.rb
      create      test/fixtures/portfolios.yml

$ rails g scaffold_controller Admin::Portfolio --model-name=Portfolio
      create  app/controllers/admin/portfolios_controller.rb
      invoke  haml
      create    app/views/admin/portfolios
      create    app/views/admin/portfolios/index.html.haml
      create    app/views/admin/portfolios/edit.html.haml
      create    app/views/admin/portfolios/show.html.haml
      create    app/views/admin/portfolios/new.html.haml
      create    app/views/admin/portfolios/_form.html.haml
      invoke  test_unit
      create    test/controllers/admin/portfolios_controller_test.rb
      invoke  helper
      create    app/helpers/admin/portfolios_helper.rb
      invoke    test_unit
      invoke  jbuilder
      create    app/views/admin/portfolios
      create    app/views/admin/portfolios/index.json.jbuilder
      create    app/views/admin/portfolios/show.json.jbuilder

This will give you a namespaced controller and views that reference the non-namespaced model.


@RubyDev was right to suggest Ryan Bate's Nifty Generators, but I don't know why he said to use the --skip-model option.

Nifty Generators will actually do exactly what you are asking for. Simply add it to your Gemfile:

gem "nifty-generators"

and run:

rails g nifty:scaffold Admin::Portfolio name:string

This will create everything a normal scaffold would with the controllers and views in an 'admin' namespace, but the model not in namespace.


rails generate model Portfolio

rails generate controller Admin::Portfolios