我正在尝试创建在每次更新中已更改为某个消息的属性日志。属性为IssueStatus
和IssueType
,两者都与UpdateAction
有两个多态关联,可以保存changed_from_id
和changed_from_type
以及changed_to_id
和changed_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为true
和save
返回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
=> []
任何帮助将不胜感激,我想我做错了什么,但我一直在考虑它太长时间才弄清楚是什么。提前谢谢!
答案 0 :(得分: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的DB中为update_id添加FK约束。