繁体   English   中英

Rails ActiveRecord-如何确定多态关系中的所有者?

[英]Rails ActiveRecord - How do I determine the owner in a polymorphic relation?

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

我将尝试在此模型上创建多态函数,该函数的行为将取决于其所有者是谁。 不幸的是,我不确定活动记录代码将是什么,当我进行绑定.pry时,self对象没有任何我可以告诉的信息。

所以一个很好的例子是Company和Person都有一个税号

当Tax ID模型将要执行某项操作时,它想知道其所有者是谁。 说得通?

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

假设以下结构,

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的帮助下。)


  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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM