Monday, February 27, 2012

Rails script/generate model with an association

I know this blog has been dormant for quite some days now for no apparent reason. But I would like to share what I learnt today. This is going to be in Rails (2.3.x) and hardly interest anyone who already knows it. But it still was a learning to me. I use to hate working in command prompt and was an IDE freak, a real good one too. But I was cornered to learn more on the command line front as well. Why waste an extra feather in the cap?
Bulling the shit, here is what I learnt today.

Rails has a script/generate ready for many usual stuff that we do. One of them is the model generator. It is not that much, but I was wondering whether it is possible to create associations using it. And I found it is not.

I tried a stupid model generation something like (in fact exactly like this)

rails -d mysql playground
cd playground
script/generate model project name:string has_many:tasks

It reeked,
exists  app/models/
exists  test/unit/
exists  test/fixtures/
create  app/models/project.rb
create  test/unit/project_test.rb
create  test/fixtures/projects.yml
create  db/migrate
create  db/migrate/20120227204200_create_projects.rb

My stupid assumption was that it would actually create a couple of models called projects and tasks. But to my wonder, it did not. The highlight was this command did not even raise any error. Inspecting the database migration, I found

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.string :name
      t.tasks :has_many


  def self.down
    drop_table :projects

And I did a migration and it did migrate without any errors. It silently ignored the line t.tasks :has_many. Not usual right?! But this is rails, you got to adapt and adapt very well. One more learning probably I could share are the commands that come with the script/generate model is the --pretend. This is like a dry run, does not actually creates a physical file but tells what its going to do. Thats it for today.