joonyou
5/17/2018 - 2:52 PM

ActiveRecord Polymorphic

ActiveRecord Polymorphic

%w(rspec active_record sqlite3 pry-byebug).each {|gem| require gem }

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3',
  :database => ':memory:' )

class CreateTestDB < ActiveRecord::Migration[5.2]
  def self.up
    create_table :foos do |t|
      t.string :name
      t.timestamps
    end

    create_table :bars do |t|
      t.string :name
      t.timestamps
    end

    create_table :comments do |t|
      t.references :commentable, polymorphic: true
      t.string :blah
      t.timestamps
    end

  end
end

CreateTestDB.migrate(:up)

class Foo < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Bar < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

RSpec.describe Foo do
  let(:foo) { Foo.create! name: "foo" }
  let(:bar) { Bar.create! name: "bar" }

  before do
    foo.comments.create blah: "foo blah blah"
    bar.comments.create blah: "bar blah blah"

  end

  it "has a comment separate from Bar" do
    expect(foo.comments.first.blah)
      .to eq "foo blah blah"

    expect(bar.comments.first.blah)
      .to eq "bar blah blah"
  end
end