0

我可能完全困惑並且在這裏脫離目標。多形性關聯混亂,通過關聯獲取資源

我有一個事件模型,has_one時間軸,belongs_to事件。時間軸has_many屬於時間軸的TimelineItems。

def Event 
    has_one :timeline 
end 

def Timeline 
    belongs_to :event 
    has_many :timeline_items 
end 

def TimelineItem 
    belongs_to :timeline 
end 

create_table :admin_timeline_items do |t| 
    t.references :admin_timeline 
    t.references :user 
    t.references :resource, :polymorphic => true 
    t.string :method 
end 

所以通過從TimelineItem對象我將能夠產生例如下面的輸出:

EML創建郵報「你好,這是EML」 [日期]

標題「嗨,這是來自eml」將來自Post對象的.title。所以例如。這TimelineItem具有這些設置

item.user = User.where(:username => "eml") 
item.resource_type = "Post" 
item.resource_id = 1 
item.created_at = 27/082...13:37 

所以問題取得被說Post對象,或者更確切地說,這個特定關聯正確的語法。對我來說似乎非常簡單,但我沒有找到我需要正確編寫的信息。

感謝您的幫助&時間。

回答

0

對不起......我只是混淆了我自己,因爲我在我自己的測試項目中設置了resource_id爲錯誤的值。我的第一個猜測是正確的。這是很簡單的:

class TimelineItem < ActiveRecord::Base 
    belongs_to :timeline 
    belongs_to :user 
    belongs_to :resource, :polymorphic => true 
end 

訪問資源,像這樣:

TimelineItem.first.resource 
=> Post(....)