![](/img/trans.png)
[英]Rails: ActiveRecord and send; how do I set an activerecord instance's relation with only knowing the class names?
[英]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.