【发布时间】:2010-02-12 23:48:23
【问题描述】:
我遇到了一些我不理解的 Rails 2.3.5 ActiveRecord 行为。似乎一个对象可以以不一致的方式更新其关联 ID。
最好用一个例子来解释:
创建具有字符串属性'title' 的Post 模型和具有字符串属性'content' 的Comment 模型。
以下是关联:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
场景#1:在下面的代码中,我创建了一个Post 和一个关联的Comment,通过Post 创建第二个Post,将第一个Comment 添加到第一个@987654331 @ 并发现第二个 Post 与第二个 Comment 相关联,但没有明确分配。
post1 = Post.new
post1 = Post.new(:title => 'Post 1')
comment1 = Comment.new(:content => 'content 1')
post1.comments << comment1
post1.save
# Create a second Post object by find'ing the first
post2 = Post.find_by_title('Post 1')
# Add a new Comment to the first Post object
comment2 = Comment.new(:content => 'content 2')
post1.comments << comment2
# Note that both Comments are associated with both Post objects even
# though I never explicitly associated it with post2.
post1.comment_ids # => [12, 13]
post2.comment_ids # => [12, 13]
场景#2:再次运行上述命令,但这次插入一个额外的命令,从表面上看,应该不会影响结果。额外的命令是post2.comments,它发生在之后创建comment2和之前将comment2添加到post1。
post1 = Post.new
post1 = Post.new(:title => 'Post 1A')
comment1 = Comment.new(:content => 'content 1A')
post1.comments << comment1
post1.save
# Create a second Post object by find'ing the first
post2 = Post.find_by_title('Post 1A')
# Add a new Comment to the first Post object
comment2 = Comment.new(:content => 'content 2A')
post2.comments # !! THIS IS THE EXTRA COMMAND !!
post1.comments << comment2
# Note that both Comments are associated with both Post objects even
# though I never explicitly associated it with post2.
post1.comment_ids # => [14, 15]
post2.comment_ids # => [14]
请注意,在这种情况下,只有 一个 评论与 post2 相关联,而在场景 1 中则有两个。
最大的问题:为什么在将新的 Comment 添加到 post1 之前运行 post2.comments 会对与 post2 关联的评论产生任何影响?
【问题讨论】:
标签: ruby-on-rails activerecord associations has-many belongs-to