Search code examples
ruby-on-railsruby-on-rails-3formscrudsti

Single Table inheritance with CRUD and forms in Rails


I'm a bit confused about STI in rails.

My situation: I have a Contact model that has description and data string fields, to store some contact like phone, fax, email, etc.

Now when I have some specific contact type like phone number of email address I want to walidate the data format in different way and I want to make some different formating on output.

I decided to use STI as all the models have the same data with just different behaviour. And I have some questions regarding forms and CRUD operations as I don't want to go against Rails conventions.

  1. How do I make a dropdown list in form with model type? Should I hardcode it or is there some more automated way?

  2. How do I create a record? Should I use switch statement and according to received type create new model of according instance?

  3. How should I update it if I'm going to change the model type? Cast the object to new class? Or create a new object and destroy the previous one?

I'll be very thankfull for your help!


Solution

    1. Yes, should do a hardcore as there no default store for your STI models.
    2. Generally, yes. But With Rails you could just use camelize.constantize to get class from string. Another way is just use parent model, and set type field manually. As with STI all records are in the same table and then all are of the parent class.
    3. If you wish to update, just update type field. Then you could re-query to force Rails to get new object of different type.