27 December 2012

Creating Ruby on Rails models

I'm actually working on a private project of my own at the moment, and this blog is serving as a means to both remember what I'm learning and share what I'm learning.  I do this in the hope that I will both help others and myself. If there are better or more efficient ways of doing things then I hope that others will share them with me in comments or via email etc.

The app I'm building uses Active Admin, so these basic instructions will include instructions for that.


When i'm creating an application, I like to get the basic model level implemented first. I want to understand the relationships between the data and get that implemented first.  Sure you can write tests and things for all this first if you're following the TDD methodology, but that's out of scope for this article.

So here's the basic process for creating Rails Active Admin models:


 bundle exec rails generate model MyModelName field_one:string two:text three:boolean  
 bundle exec rails generate model Blog title:string body:text active:boolean  

The above will generate a migration file in your <application_root>/db/migrate folder.  The file will be date/time stamp of numbers combined with a create_<your model name>.rb file.

eg: 20121226195102_create_news.rb

The model generation will also create an app_root/app/models/<your model name>.rb file, and if you're using rspec then it will also generate a spec/models/<your model name> file.

Next, after generating a migration file there are two choices. If you want to add database level constraints such as null (true/false) or default values, edit the migration file and add them.

 bundle exec rake db:migrate  

The above command actually runs the 'migration' and creates the tables in the database for you.


 bundle exec rails generate active_admin:resource ModelName  

Now that you have database tables, the above command creates a basic CRUD admin interface for your model.

I find this final step a nice way of validating in my head if my model has all the right fields.

After doing these steps your models are not finished, but you've at least made a start.
Next you can add validations and model associations, but that is for another article.

Oh and I should add, the Ruby on Rails Guides has a great article on migrations.

TL;DR


 bundle exec rails generate model MyModelName field_one:string two:boolean  
 bundle exec rails generate model Blog title:string body:text active:boolean  
 bundle exec rake db:migrate  
 bundle exec rails generate active_admin:resource ModelName  

No comments:

Post a Comment