I was wondering if anybody knew of a way to do something like the following:
rails generate model Foo name:string, validates: {:name, uniqueness: true}
That is, whilst declaring a model generator with some attributes, work some rails magic to add your validations at the same time.
There isn't. The rails generate model command is directly tied to database functionality. For example, you should be able to do a command like this rails generate model Foo name:string:uniq. This would force the database to require a unique string for the name. This wouldn't add anything to your foo.rb file.
Here is some more information about rails model generations: http://travisjeffery.com/b/2012/03/generate-rails-migrations-that-automagically-add-your-change/
As others have said, there isn't currently a way to do this. Most of the special options for the rails generate model
command are parsed by the parse_type_and_options
method in generated_attribute.rb. The model_generator.rb will then build the model and migration files using this info.
The template for the model file that is created is model.rb. In Rails 4 this template can add in special code for belongs_to
, polymorphic
, and has_secure_password
but not code related to validations.
The template for the migration file that is created is create_table_migration.rb. In Rails 4 this can add in special options for limit
, decimal
, and precision
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With