mrj*_*ke2 7 ruby orm activerecord persistence ruby-on-rails
在我将这个错误发布给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
Run Code Online (Sandbox Code Playgroud)
我的模型如下:
class Post < ActiveRecord::Base
has_many :comments, :autosave => true
end
class Comment < ActiveRecord::Base
belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)
在控制台中,我运行以下命令(此时post和comments对象已经在DB中):
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
Run Code Online (Sandbox Code Playgroud)
但这是我得到的输出:
post.title # => "On the migration of ducks"
post.comments.last.body # => "Actually, your article should be named differently."
Run Code Online (Sandbox Code Playgroud)
此外,查看日志这是我看到的唯一更新声明:
更新后(0.6ms)UPDATE"posts"SET"updated_at"='2010-01-18 23:32:39',"title"='关于鸭子的迁移'WHERE"id"= 1
因此看起来保存没有级联到评论对象,这似乎对我来说很明显.我在运行2.3.4的两个不同系统上尝试了这个,并且行为是可重复的.
不过这是一个奇怪的部分:如果我在尝试设置值之前首先调用"post.comments",它就可以了!确切地说:
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
Run Code Online (Sandbox Code Playgroud)
现在输出给了我正确的结果:
post.title # => "On the migration of ducks"
post.comments.last.body # => "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
Run Code Online (Sandbox Code Playgroud)
并且日志包含正确的更新:
评论更新(0.3ms的)UPDATE "意见" SET "的updated_at"= '2010-01-18 23点44分43秒', "身体"="其实,你的文章应该有不同的名称.[更新]:你是对的,谢谢.WHERE"id"= 2
所以这对我来说真的很糟糕.我猜测,它与引用处理该对象,一旦对象是分配的集合的一部分它保存很好,但是当它被拉到从数据库中的单个对象不保存方式,即一个问题.但在此之前我提出这个Rails的团队中的错误,我想看看其他人已经遇到了这个问题,或者如果我只是在做一些完全愚蠢的是,我没有看到,因为我整天都在这.
这种情况很常见,是可以预料到的,而且解决方法也很简单:
last_comment = post.comments.last
last_comment.body = "[totally awesome dream hands]"
last_comment.save
Run Code Online (Sandbox Code Playgroud)
不是很简洁,但很实用:)
| 归档时间: |
|
| 查看次数: |
1309 次 |
| 最近记录: |