How to avoid Rails scaffold to place model into namespace

Viewed 16734

Rails 3 scaffold generator places model classes inside namespace. Example:

rails generate scaffold admin/portfolio

But I want only controllers and views to be placed inside admin namespace.

How can I avoid that?

8 Answers

You can do this now on Rails (or at least on 5.1) using the following command:

rails g scaffold_controller admin/portfolio --model-name=Portfolio

By specifying --model-name Rails does not automatically tries to guess the model name.

You can fairly simply create your own generators and do whatever you want with them:

In Rails 4:

#config/application.rb
config.generators do |g|
  g.scaffold_controller :my_controller
end

and

#lib/generators/rails/my_controller/my_controller_generator.rb
class Rails::MyControllerGenerator < Rails::Generators::ScaffoldControllerGenerator
  def class_name
   ([file_name]).map!{ |m| m.camelize }.join('::')
  end

  def table_name
    @table_name ||= begin
      base = pluralize_table_names? ? plural_name : singular_name
      ([base]).join('_')
    end
  end
end

Will remove the model namespacing.

Bear in mind if you are generating a scaffold_controller on its own you'll need to explicitly call your custom generator: rails g my_controller 'account/users'

Unfortunately this only handles the controller. I'm still searching for a view solution.

Related