Last active
July 19, 2018 13:41
-
-
Save joonyou/1b2111af84aee9cb2462d9eb94835f20 to your computer and use it in GitHub Desktop.
ActiveRecord Polymorphic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment