1

我有一个模型可以由许多其他模型拥有(它有很多外键)。

我将尝试在这个模型上创建一个多态函数,它的行为取决于它的所有者是谁。不幸的是,我不确定要找出什么活动记录代码,当我进入 binding.pry 时,self 对象没有任何我能告诉的信息。

所以一个很好的例子是公司和个人都有一个税号

当 Tax ID 模型要做某事时,它想知道它的所有者是谁。说得通?

我的实际关系是has_many,但我怀疑这是症结所在。

4

2 回答 2

3

假设以下结构,

class Tax
  belongs_to :taxable, polymorphic: true
end

class Company
  has_many :taxes, as: :taxable
end

class Person
  has_many :taxes, as: :taxable
end

create_table :taxes do |t|
  t.integer :taxable_id
  t.string  :taxable_type
  t.timestamps
end

每个税务记录都可以使用tax.taxable. 要获取类型,请使用

tax.taxable.class.name

或者

tax.taxable_type

(在@SteveTurczyn 和@MrYoshiji 的帮助下。)

于 2013-08-02T15:42:17.993 回答
0

  class Tax
    belongs_to :taxable, :polymorphic => true  # tax table needs taxable_type taxable_id
  end

class Company has_one :tax, :as => :taxable end

class Person has_one :tax, :as => :taxable end

Tax.first.taxable

于 2013-08-02T14:27:57.077 回答