2010-01-19 55 views
7

在我把这个作为一个bug发布到rails团队之前,我想看看我是否做了可能导致这种行为的错误。具体来说,has_many关联的:autosave属性似乎不按照文档工作。:在Rails 2.3.4中破坏has_many关联的自动保存属性?

仅供参考,这里是最新的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 = 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." 

而且,看在日志中,这是唯一的更新语句我看到:

帖子消息(0.6ms)UPDATE “上岗” 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 

现在输出给了我正确的结果:

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 “意见” SET “updated_at”='2010-01-18 23:44:43',“body”='其实,你的文章应该有不同的命名。 [已更新]:你说得对,谢谢。'在哪里“ID”= 2

所以这真的看起来打破了我。我猜测这是处理对象引用的一个问题,也就是说,一旦对象是分配集合的一部分,它就可以很好地保存,但当它从数据库中作为单个对象提取时,它不会保存。但在我将这个问题提交给Rails团队之前,我想看看是否有其他人遇到了这个问题,或者如果我只是在做一些完全骨头的事情,而我没有看到,因为我已经花了整整一天的时间。

+0

我不认为你可以邮寄一份错误的Rails 2.3.4,因为它甚至不是2.3系列的最后一个稳定版本。有可能是在AutosaveAssociation模块中修复了一个错误。我甚至怀疑他们会在2.3.11中对此进行修正。 – 2011-05-31 18:47:24

回答

0

这是很常见的可以预期的,而解决办法很简单:

last_comment = post.comments.last 
last_comment.body = "[totally awesome dream hands]" 
last_comment.save 

不是很简洁,但功能:)

相关问题