【问题标题】:Polymorphic relationship - what is stored in the type attribute?多态关系——类型属性中存储了什么?
【发布时间】:2014-06-24 04:10:32
【问题描述】:

假设你有这样的多态关系:

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

class Employee < ActiveRecord::Base
  has_many :pretty_pictures, as: :imageable
end

class ProductInvoice < ActiveRecord::Base
  has_many :pretty_pictures, as: :imageable
end

这是您对 Picture 模型的迁移:

class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      t.string :name
      t.references :imageable, polymorphic: true
      t.timestamps
    end
  end
end

假设您有一个 :id 为 1 的@product_invoice,并且您有一个属于该产品的@picture。我知道@picture.imagable_id 应该等于1,但是@picture.imagable_type 中存储的值是什么?

  • “产品发票”
  • “产品发票”
  • 'product_invoice'
  • 'product_invoices'

【问题讨论】:

    标签: ruby-on-rails-4 polymorphism has-many polymorphic-associations belongs-to


    【解决方案1】:

    通过 cmets 中的 GB

    '产品发票'

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 2020-10-17
      相关资源
      最近更新 更多