user6528504
user6528504

Reputation:

Rails Alternative to use polymorphic associations

I've see that the polymorphic association break the rules of relational db design and in the end cause more harm to the app. so, the left alternative is using STI. someone can please explain how STI works or know if there is another good alternative in using polymorphic association?

thank's

Upvotes: 1

Views: 956

Answers (1)

VAD
VAD

Reputation: 2401

About STI

When you're using STI, you have one parent model which has its own table in DB. And then you have several submodels. But they don't have own tables. Instead their objects are stored in the table of the parent model.

Let's take a look at the example

Generate parent model Vehicle. Add the type column to it. That column will be used for storing the name of the submodel to which belongs corresponding object.

$ rails generate model vehicle type:string color:string price:decimal{10.2}

Then generate submodels telling that Vehicle is their parent model:

$ rails generate model car --parent=Vehicle
$ rails generate model truck --parent=Vehicle

You'll get the following models:

class Car < Vehicle
end

class Truck < Vehicle
end

Now when you create new car it will be stored in the vehicles table and will have 'car' in the type column. Trucks will be stored in the vehicles table too. But they'll have 'truck' in the type column.

About good and bad alternatives.

You know, STI isn't a silver bullet and is considered as pretty bad practice too. For example it can make the table of your parent model the cluttered nightmare. It can prevent you from indexing your data effectively and so on.

Truth is you can use the certain practice when it fits your needs. STI is good when you have mostly the same submodels maybe with slightly different behavior. In that case your table will be neat and your data will be organized naturally and you will not get much harm.

Upvotes: 1

Related Questions