Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails generate model including validations?

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.

like image 568
DazBaldwin Avatar asked Oct 03 '22 06:10

DazBaldwin


2 Answers

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/

like image 147
Kyle Avatar answered Oct 23 '22 08:10

Kyle


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.

like image 1
cschroed Avatar answered Oct 23 '22 07:10

cschroed