text ActiveRecord Polymorphic

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 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

以上是关于text ActiveRecord Polymorphic的主要内容,如果未能解决你的问题,请参考以下文章

Rails ActiveRecord::Base before_save 覆盖 write_ 访问器以保存电话号码

ActiveRecord::使用默认值存储

仅列出 ActiveRecord 子类方法

找不到 id=#<ActiveRecord::Relation::ActiveRecord_Relation_User:0x2eb9b58> 的用户

找不到 ActiveRecord\MysqliAdapter

Castle ActiveRecord学习