加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – :在Rails 2.3.4中打破了has_many关联的自动保

发布时间:2020-12-16 21:10:34 所属栏目:百科 来源:网络整理
导读:在我将这个错误发布给rails团队之前,我想知道我是否做错了可能导致此行为的错误.具体来说,has_many关联的:autosave属性似乎没有按照文档工作. 作为参考,这是最新的API文档: http://api.rubyonrails.org/classes/Acti … ation.html 看一下“一对多示例”部
在我将这个错误发布给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和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

但这是我得到的输出:

post.title # => "On the migration of ducks"
  post.comments.last.body # => "Actually,your article should be named differently."

此外,查看日志这是我看到的唯一更新声明:

更新后(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,thanks."

  post.save 
  post.reload

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

post.title # => "On the migration of ducks"
  post.comments.last.body # => "Actually,thanks."

并且日志包含正确的更新:

评论更新(0.3ms)UPDATE“comments”SET“updated_at”=’2010-01-18 23:44:43′,“body”=’实际上,您的文章的名称应该不同. [更新]:你是对的,谢谢. WHERE“id”= 2

所以这对我来说真的很糟糕.我猜测对象引用的处理方式存在问题,即一旦对象成为已分配集合的一部分,它就可以保存,但是当它作为单个对象从数据库中提取时不会保存.但在我将这个提交给Rails团队作为一个错误之前,我想看看是否有其他人遇到过这个问题,或者我只是做了一些完全愚蠢的事情,我没有看到因为我花了一整天时间.

解决方法

这是很常见的预期,并且工作很简单:
last_comment = post.comments.last
last_comment.body = "[totally awesome dream hands]"
last_comment.save

不是很简洁,但功能:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读