2013-08-02 19 views
1

我有一個模型可以被許多其他模型擁有(它有很多外鍵)。Rails ActiveRecord - 如何確定多態關係中的所有者?

我要試着在這個模型上做一個多態函數,這將取決於它的所有者是誰。不幸的是,我不確定活動的記錄代碼是如何發現的,以及何時進入binding.pry,自我對象沒有任何信息。

因此,一個很好的例子是單位和個人都有一個稅號

當稅號模型要做些什麼,它想知道這是誰所有者。說得通?

我的實際關係是has_many,但我懷疑這是關鍵。

+0

通常,在多態關聯,你有兩列' _type'和' _id'。所以我猜你在Tax表中可以找到這2列(在你的案例中是'owner_type'和'owner_id') – MrYoshiji

+0

@MrYoshji - 你是對的,但是在做binding.pry時,我看着自己的對象,看看哪個父母id被設置,無濟於事。 我覺得有一些東西可以使代碼更清潔,但我真的找不到它。 – GantMan

+0

當您執行綁定pry時,請查看多態列(可能是'taxable_type'),它應該告訴您與之關聯的模型。 – SteveTurczyn

回答

-1

 
    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

+0

你說得對,has_one vs has_many無所謂..使用 –

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幫助。)

+0

哇!好吧,非常明確!愛它! – GantMan

相關問題