【发布时间】:2011-01-06 14:49:47
【问题描述】:
在我将此作为 bug 发布到 rails 团队之前,我想看看我是否做错了可能导致这种行为的事情。具体来说,has_many 关联的 :autosave 属性似乎没有按照文档工作。
作为参考,这里是最新的 API 文档: http://api.rubyonrails.org/classes/Acti…ation.html
查看“一对多示例”部分。我已经在测试应用程序中复制了那里的代码,但它对我不起作用。具体来说,父对象会更新,而子对象不会。
我的架构如下:
create_table :posts do |t|
t.string :title
t.timestamps
end
create_table :comments do |t|
t.text :body
t.integer :post_id
t.timestamps
我的模型如下:
class Post < ActiveRecord::Base
has_many :comments, :autosave => true
end
class Comment < ActiveRecord::Base
belongs_to :post
end
在控制台中,我运行以下命令(此时 post 和 cmets 对象已经在数据库中):
post = Post.find(1)
post.title # => "The current global position of migrating ducks"
post.comments.first.body # => "Wow, awesome info thanks!"
post.comments.last.body # => "Actually, your article should be named differently."
post.title = "On the migration of ducks"
post.comments.last.body = "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
post.save
post.reload
但这就是我得到的输出:
post.title # => "On the migration of ducks"
post.comments.last.body # => "Actually, your article should be named differently."
此外,查看日志,这是我看到的唯一更新语句:
Post Update (0.6ms) UPDATE "posts" SET "updated_at" = '2010-01-18 23:32:39', "title" = '关于鸭子的迁移' WHERE "id" = 1
所以看起来保存并没有级联到 cmets 对象,这对我来说似乎很明显被破坏了。我已经在运行 2.3.4 的两个不同系统上进行了尝试,并且该行为是可重复的。
不过,奇怪的是:如果我在尝试设置值之前先调用“post.cmets”,它就可以正常工作!准确地说:
post.title = "On the migration of ducks"
post.comments #Note that this line was not called above
post.comments.last.body = "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
post.save
post.reload
现在输出给了我正确的结果:
post.title # => "On the migration of ducks"
post.comments.last.body # => "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
并且日志包含正确的更新:
评论更新(0.3ms) UPDATE "cmets" SET "updated_at" = '2010-01-18 23:44:43', "body" = '其实你的文章应该换个名字。 [更新]:你是对的,谢谢。 WHERE "id" = 2
所以这对我来说真的很糟糕。我猜这是处理对象引用的方式的问题,即一旦对象是已分配集合的一部分,它可以很好地保存,但当它作为单个对象从数据库中提取时不会保存。但在我将此作为错误提交给 Rails 团队之前,我想看看是否有其他人遇到过这个问题,或者我是否只是在做一些我没有看到的完全愚蠢的事情,因为我已经花了一整天的时间.
【问题讨论】:
-
我认为你不能发布 Rails 2.3.4 的错误,因为这甚至不是 2.3 系列的最后一个稳定版本。 AutosaveAssociation 模块中可能存在已修复的错误。我什至怀疑他们会在 2.3.11 中对此进行错误修复。
标签: ruby-on-rails ruby activerecord orm persistence