gpt4 book ai didi

ruby-on-rails - Rails ActiveRecord : Does accepts_nested_attributes_for mark a parent record as dirty even if parent attributes are unchanged?

转载 作者:行者123 更新时间:2023-12-03 15:53:56 34 4
gpt4 key购买 nike

我正在与 iPhone 应用程序同步数据,因此了解哪些记录已“实际”更新而哪些尚未更新非常重要。我有一个带有相关链接关联的事件模型:

在 event.rb 中:

has_many :related_links
accepts_nested_attributes_for :related_links, :reject_if => lambda { |a| a[:url].blank? && a[:id].blank? }, :allow_destroy => true

在我的事件表单上,当我什么都没有改变时,包括相关链接字段,我很好......我的事件模型没有任何更新。但是如果我在我的相关链接字段中输入一个 url,我的事件对象上的“updated_at”就会更新。
UPDATE "events" SET "updated_at" = '2011-05-30 15:27:03.228435' WHERE "events"."id" = 1791

它应该这样工作吗?我可以阻止它被标记为脏和被更新吗?

最佳答案

如果父模型的属性没有改变,那么记录不被认为是脏的,并且 updated_at不应该改变。以此为例(Rails 3.2.3)

后模型

class Post < ActiveRecord::Base
attr_accessible :title, :body, :comments_attributes

has_many :comments
accepts_nested_attributes_for :comments
end

评论模型
class Comment < ActiveRecord::Base
attr_accessible :body, :author
belongs_to :post
end

Rails 控制台测试(我只在粘贴时保留了相关输出)
1.9.3p194 :001 > p = Post.create :title => "Nested attributes", :body => "Nested attributes are awesome", :comments_attributes => [{ :body => "I agree", :author => "Bart" }]
=> #<Post id: 1, title: "Nested attributes", body: "Nested attributes are awesome", created_at: "2012-06-13 01:49:34", updated_at: "2012-06-13 01:49:34">

1.9.3p194 :002 > last_post = Post.last
=> #<Post id: 1, title: "Nested attributes", body: "Nested attributes are awesome", created_at: "2012-06-13 01:49:34", updated_at: "2012-06-13 01:49:34">

1.9.3p194 :003 > last_post.comments_attributes = [{:id => 1, :author => "Bort"}]
=> [{:id=>1, :author=>"Bort"}]

1.9.3p194 :004 > last_post.changed?
=> false

1.9.3p194 :005 > last_post.save
(0.1ms) begin transaction
(0.7ms) UPDATE "comments" SET "author" = 'Bort', "updated_at" = '2012-06-13 01:51:05.032862' WHERE "comments"."id" = 1
(250.1ms) commit transaction
=> true

1.9.3p194 :006 > last_post.updated_at
=> Wed, 13 Jun 2012 01:49:34 UTC +00:00

因此,在您的情况下,肯定还有其他原因导致在 Event 上触发更新。 .查看是否有 callbacks可能正在这样做,并检查您的 belongs_to 是否方法未定义为 :touch选项。例如
belongs_to :event, :touch => true

关于ruby-on-rails - Rails ActiveRecord : Does accepts_nested_attributes_for mark a parent record as dirty even if parent attributes are unchanged?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178258/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com