PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 14, 2022

[FIXED] How to change a reference column to be polymorphic?

 April 14, 2022     activerecord, migration, ruby-on-rails, ruby-on-rails-2     No comments   

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.

I figure I have two options:

  • Create new reference column fooable which is polymorphic and migrate the ID's from foo_id (What would be the best way to migrate these? Could I just do Bar.each { |b| b.fooable_id = b.foo_id }?
  • Rename foo_id to fooable_id and add polymorphic to fooable_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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing