There are two ways to write a polymorphic migration in Rails. Generally, I’ve done this:
class CreateFeatures < ActiveRecord::Migration
def change
create_table :features do |t|
t.integer :featureable_id
t.string :featurable_type
t.timestamps
end
end
end
However, we can also do this:
class CreateFeatures < ActiveRecord::Migration
def change
create_table :features do |t|
t.references :featureable, :polymorphic => true
t.timestamps
end
end
end
The two are, for all practical purposes, identical. My question: Is one better than another? Is one better for future maintainability?
This would likely be an issue only if one of two things changed:
- The polymorphic abstraction version (Version #2) goes away or the syntax changes
- The method of working a polymorphic relationship (using id and type) changes- unlikely
Just wondering if there’s a preference, or if it’s “Meh, doesn’t really matter either way”
For an all rails app, where you are generating all tables via migrations, there is no difference functionally.
Here is the code for references:
This is all well and good but if your foreign keys on the referenced table are not _id, method one is the only choice.
references just saves you one line of code…