簡體   English   中英

has_many / belongs_to關聯由於多態關聯而無法保存?

[英]Has_many/belongs_to association not saving due to polymorphic associations?

我正在嘗試創建在每次更新某條消息時已更改的屬性的日志。 這些屬性是IssueStatusIssueType ,它們都有兩個與UpdateAction多態關聯,這兩個屬性完美地保存了changed_from_idchanged_from_type以及changed_to_idchanged_to_type

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

問題是嘗試將UpdateAction保存到Update.update_actions不起作用。 Rails對於savesave!均返回true save! ,但我的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
=> []

任何幫助將不勝感激,我想我做錯了什么,但是我一直在尋找很長時間才能弄清楚是什么。 提前致謝!

從更改第一行

action = UpdateAction.new

action = Update.last.update_actions.build

這就是您的示例中發生的事情(假設您引用的是真實的u,而不是Swanand建議的更新)-u.save行什么也不做,因為它僅保存未保存的關聯對象。 您已經保存了一個退化動作,因此保存在has_many上的關聯對象不認為有任何工作要做,因為需要更改的字段位於關聯對象中。 因此,沒有將action_update_id字段保存在何處。 您也可以調用action.save並修復它。

我將擁有validate_presence_of update_id來防止保存並在數據庫中針對update_id的update_actions添加FK約束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM