Issue
My model (Bar) already has a reference column, let's call it foo_id
and now I need to change foo_id
to fooable_id
and make it polymorphic.
- Create new reference column
fooable
which is polymorphic and migrate the ID's fromfoo_id
(What would be the best way to migrate these? Could I just doBar.each { |b| b.fooable_id = b.foo_id }?
- Rename
foo_id
tofooable_id
and addpolymorphic
tofooable_id
. How to add polymorpic to an existing column?
Solution
1. Change the name of foo_id to fooable_id by renaming it in a migration like:
rename_column :bars, :foo_id, :fooable_id
2. and add polymorphism to it by adding the required foo_type column in a migration:
add_column :bars, :fooable_type, :string
3. and in your model:
class Bar < ActiveRecord::Base
belongs_to :fooable,
polymorphic: true
end
4. Finally seed the type of you already associated type like:
Bar.update_all(fooable_type: 'Foo')
Read Define polymorphic ActiveRecord model association!
Answered By - Christian Rolle Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.