gpt4 book ai didi

ruby-on-rails - rails 协会 :autosave doesn't seem to working as expected

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:44 29 4
gpt4 key购买 nike

我做了一个真正的基础github项目here这说明了这个问题。基本上,当我创建一个新评论时,它会按预期保存;当我更新现有评论时,它不会被保存。然而,这不是 :autosave => true 的文档所说的……他们说的恰恰相反。这是代码:

class Post < ActiveRecord::Base
has_many :comments,
:autosave => true,
:inverse_of => :post,
:dependent => :destroy

def comment=(val)
obj=comments.find_or_initialize_by(:posted_at=>Date.today)
obj.text=val
end
end

class Comment < ActiveRecord::Base
belongs_to :post, :inverse_of=>:comments
end

现在在控制台中,我测试:

p=Post.create(:name=>'How to groom your unicorn')
p.comment="That's cool!"
p.save!
p.comments # returns value as expected. Now we try the update case ...

p.comment="But how to you polish the rainbow?"
p.save!
p.comments # oops ... it wasn't updated

为什么不呢?我错过了什么?

请注意,如果您不使用“find_or_initialize”,它会像 ActiveRecord 尊重关联缓存一样工作 - 否则它会过于频繁地重新加载注释,从而丢弃更改。即,此实现有效

def comment=(val)
obj=comments.detect {|obj| obj.posted_at==Date.today}
obj = comments.build(:posted_at=>Date.today) if(obj.nil?)
obj.text=val
end

但是,当然,如果我可以只使用数据库,我不想遍历内存中的集合。另外,它适用于新对象而不适用于现有对象,这似乎不一致。

最佳答案

这是另一种选择。如果不是新记录,您可以将 find_or_initialize_by 返回的记录显式添加到集合中。

def comment=(val)
obj=comments.find_or_initialize_by(:posted_at=>Date.today)
unless obj.new_record?
association(:comments).add_to_target(obj)
end
obj.text=val
end

关于ruby-on-rails - rails 协会 :autosave doesn't seem to working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455173/

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