Tuesday 6 September 2011

First steps with Rails: Inheritance

So I went back to my Rails code trying to figure out how to do the inheritance with scaffold.

Turns out... you can't do it :S (or at least I couldn't find an article on how to do it and all examples show a different path). You can specify the --parent attribute but it won't create the necessary migrations and the auto-generated CRUD pages will only contain the new fields.
So what I did was this:
I run

rails g scaffold TwitterUser --parent=User

That creates the class TwitterUser<User and the htmls for it. After that I had to manually create a migration. Rails uses STI out of the box, so I used that :P

My new migration had to add a column type of type string you have to use that name so rails will set the subclass name automatically for you.

After that you can add your custom columns.

class AddAndRemoveTwitterUserColumnsToUser < ActiveRecord::Migration
  def up
    add_column :users, :twitterName, :string
    add_column :users, :twitter_Id, :integer
    add_column :users, :type, :string
  end
  def down
    remove_column :users, :twitterName
    remove_column :users, :twitter_Id
    remove_column :users, :type
  end
end

After that you can go to your app/view and change the html and support the new fields. It's not that hard but I thought that scaffold tool could have done the work for me.


No comments:

Post a Comment