Cror2014
Cror2014

Reputation: 447

How to change an association in rails

I wanted to know if I build an association between two models and later find out that I should change it, what should I do then? For example, if there is a has_one and belongs_to associations between two models and then I find out that it should be has_many, what should I do? Should I create a new migration, beside changing those terms in the models' files? If so, what should I write inside the migration file? where else should I make changes?

Thanks in Advance.

Upvotes: 1

Views: 3351

Answers (3)

neo
neo

Reputation: 4116

For example if you had:

class Foo
 has_many :bars #or has_one :bar
end

Another class:

class Bar
 belongs_to :foo
end

On your database, you'll need to add a column foo_id on your bars table but you won't need bar_id column on your foos table. So if you decide to transpose the relationship, just need to add that column on foos table.

I would recommend that you plan things out first before running migrations.

Kinda like:

    1) Foo
         - post:string
         - somethingelse:integer

         has_many :bars or has_one :bar

    2) Bar
         - something:boolean
         - else:string
         - foo_id:integer

         belongs_to :foo

Now you know what to run when you create your models you can run migrations right away.

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36860

There's actually no changes needed to the data files... you already have a foreign key in the has_one (singular) target model, so you can just change it to a has_many (plural)in the model definition.

Where you reference the association, for example book.owner you would have to use the plural term book.owners and the response will be an array of objects instead of a single object.

All your existing relationships will automatically change... where you had one owner for a book, you'll still have one owner of a book but it'll be in an array and you'll be able to add more owners now.

Upvotes: 0

Ahmad Al-kheat
Ahmad Al-kheat

Reputation: 1795

If you want to change from has_one to has_many, then I think all you need to do is change the association is your model to has_many, however if you want to change the belongs_to, that's when you will need to rollback that specific migration and create a new one according to the new association

Upvotes: 0

Related Questions