理解できない Rails 2.3.5 ActiveRecord の動作に遭遇しました。オブジェクトのアソシエーション ID が一貫性のない方法で更新される可能性があるようです。
これは、次の例で最もよく説明されています。
Post
string 属性'title'
を持つComment
モデルとstring 属性を持つモデルを作成します'content'
。
協会は次のとおりです。
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
シナリオ #1: 次のコードPost
では、関連付けられた を使用して 1 つを作成し、1 つComment
目Post
をfind
'ing して 2 つ目を作成し、1 つ目に 2 つ目Comment
を追加して、明示的な割り当てなしで2 つ目が関連付けられていることPost
を発見します。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: 上記のコマンドを再度実行しますが、今回は結果に影響を与えない追加のコマンドを 1 つ挿入します。追加のコマンドは、作成後、に追加する前に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]
シナリオ 1 では 2 つのコメントがあったのに対し、このシナリオでは1 つのコメントしか関連付けられていないことに注意してください。post2
大きな疑問:新規をpost2.comments
追加する前に実行して、どのコメントが に関連付けられているかに違いがあるのはなぜですか?Comment
post1
post2