Search code examples
ruby-on-railsrails-generaterails-generators

How to pass class_name Option to Generator?


I am using Rails' generators to produce things like models in my app.

My models are commonly using the class_name option on relations.

Is it possible to generate a model from the command line and pass the value for class_name? I specifically want to avoid modifying the model after the generator runs.

An example of what I hope exists is something like:

rails generate model Book title:string author:belongs_to{class_name:User}

Then the generated Book model would look like:

class Book < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
end

Solution

  • No, you can't pass class_name as an option to the generator. It is not a valid option to the generator command. You can see the list of available options by running

    rails g model --help
    

    I believe the only way is to manually edit the models to specify the class_name