2009-12-02 130 views
0

我試圖創建一個日誌已每次更新中更改爲某個消息的屬性。屬性爲IssueStatusIssueType,並且都與UpdateAction有兩個多態關聯,這就完美地節省了changed_from_idchanged_from_type以及changed_to_idchanged_to_typeHas_many/belongs_to關聯由於多態關聯而不能保存?

class IssueStatus < ActiveRecord::Base 
    has_many :update_actions, :as => :changed_to 
    has_many :update_actions, :as => :changed_from 
end 

class IssueType < ActiveRecord::Base 
    has_many :update_actions, :as => :changed_to 
    has_many :update_actions, :as => :changed_from 
end 

class Update < ActiveRecord::Base 
    has_many :update_actions 
end 

class UpdateAction < ActiveRecord::Base 
    belongs_to :changed_to, :polymorphic => true 
    belongs_to :changed_from, :polymorphic => true 

    belongs_to :update 
end 

的問題是,試圖保存UpdateActionUpdate.update_actions不起作用。對於savesave!,Rails返回true,但是我的development.log顯示沒有執行SQL查詢。我找不到我做錯了什麼,因爲沒有記錄(或者我不知道如何找到它)。從控制檯工作:

>> action = UpdateAction.new 
=> #<UpdateAction id: nil, changed_from_id: nil, changed_from_type: nil, changed_to_id: nil, changed_to_type: nil, update_id: nil, created_at: nil, updated_at: nil> 
>> action.changed_from = from 
=> #<IssueStatus id: 2, name: "Open", created_at: "2009-12-02 05:34:41", updated_at: "2009-12-02 05:34:41"> 
>> action.changed_to = to 
=> #<IssueStatus id: 1, name: "Closed", created_at: "2009-12-02 05:34:30", updated_at: "2009-12-02 05:34:30"> 
>> action.save 
=> true 
>> update = Update.last 
=> #<Update id: 1, description: "Yawn", created_at: "2009-12-02 05:19:25", updated_at: "2009-12-02 05:19:25"> 
>> u.update_actions << action 
=> [#<UpdateAction id: 2, changed_from_id: 2, changed_from_type: "IssueStatus", changed_to_id: 1, changed_to_type: "IssueStatus", update_id: 1, created_at: "2009-12-02 05:35:16", updated_at: "2009-12-02 05:35:16">] 
>> u.save 
=> true 
>> u.update_actions 
=> [#<UpdateAction id: 2, changed_from_id: 2, changed_from_type: "IssueStatus", changed_to_id: 1, changed_to_type: "IssueStatus", update_id: 1, created_at: "2009-12-02 05:35:16", updated_at: "2009-12-02 05:35:16">] 
>> u.reload 
=> #<Update id: 1, description: "Yawn", created_at: "2009-12-02 05:19:25", updated_at: "2009-12-02 05:19:25"> 
>> u.update_actions 
=> [] 

任何幫助,將不勝感激,我想我做錯了,但我一直在尋找它太長弄清楚什麼。提前致謝!

+0

u.update_actions << action'是update.update_actions << action'的拼寫錯誤嗎? – Swanand 2009-12-02 07:55:54

+0

是的,這次我混淆了它們,但它並沒有改變這個問題。 – Janteh 2009-12-02 09:25:26

回答

3

action = UpdateAction.new 

action = Update.last.update_actions.build 

這裏的什麼發生在你的榜樣更改您的第一行(假設你引用一個真正的U,不更新爲Swanand建議) - 在u.save行不做任何事情,因爲它只保存未保存的關聯對象。你已經保存了一個墮落的動作,因此相關的對象上保存的has_many不認爲有什麼工作要做,因爲這需要改變字段是關聯的對象。所以,沒有保存update_id字段的地方。你也可以調用action.save並修復它。

我會validate_presence_of UPDATE_ID防止保存在數據庫上update_actions添加FK約束的UPDATE_ID。

+1

感謝您爲我解決這個問題。現在有道理。不勝感激! – Janteh 2009-12-03 06:51:33