fibono
fibono

Reputation: 783

Default Values for Child-Class Attributes in Rails

Say in my schema I have a users table with an attribute field of pets that's default to ["dogs"]:

create_table "users", force: true do |t|
    ...
    t.text    "pets",     default: ["dogs"],    array: true
    ...

I have a model FriendlyUser that inherits from class User: class FriendlyUser < User

Thus, when a FriendlyUser is created, the type is "FriendlyUser". But I would like FriendlyUser to have pets set to a default of dogs AND cats: ["dogs", "cats"]

Is this possible with a migration, or must this be done in the class (by overriding an initialize method, using after_initialize, before_create, etc)?

Upvotes: 3

Views: 533

Answers (2)

Reyko
Reyko

Reputation: 201

Since STI is using one table for multiple models, default values in the database layer will make it harder for your models to have different characteristics. Thus, I think you should stick with moving the default value logic to your application logic where you can define model specific behaviour.

Upvotes: 2

Anthony E
Anthony E

Reputation: 11235

Default values in Rails migrations aren't intended to handle logic like this. From the database side, it might be technically possible using a trigger to populate the data on insert based on the value in the type column, but that's probably more trouble and complication than it's worth.

Setting the value in a before_validation callback is probably your best bet. And since you're using inheritance you can override the callback in the subclass.

Upvotes: 2

Related Questions