$ rails -v
Rails 3.1.1
$ ruby -v
ruby 1.9.2p312 (2011-08-11 revision 32926) [i686-linux]
問題を再現したい場合は、私に従ってください:
まず、次の3つのモデルを作成します(コピーするだけです)。
#school.rb
class School
include Mongoid::Document
include Mongoid::Timestamps
has_many :students
end
#student.rb
class Student
include Mongoid::Document
include Mongoid::Timestamps
has_many :books
belongs_to :school
accepts_nested_attributes_for :books
end
#book.rb
class Book
include Mongoid::Document
include Mongoid::Timestamps
field :name
belongs_to :student
validate :check
def check
# The calling for the 'school' method caused the issue
self.student.school
end
end
次に、コンソールを実行して貼り付けます。
ruby-1.9.2-head :001 > School.destroy_all;Student.destroy_all; Book.destroy_all; School.create
ruby-1.9.2-head :001 > Student.create school_id: School.first.id, 'books_attributes' => {'1' => {'name' => 'I am a book'}}
次に、何が起こったのか見てみましょう。
ruby-1.9.2-head :002 > Book.count
MONGODB xxx_development['$cmd'].find({"count"=>"books", "query"=>{}, "fields"=>nil})
=> 2
さらに、「student has_manybooks」リレーションを「autosave:true」に設定すると、次のようになります。
class Student
......
has_many :books, autosave: true
......
end
何が起こるか見てみましょう:
ruby-1.9.2-head :001 > School.destroy_all;Student.destroy_all; Book.destroy_all; School.create
ruby-1.9.2-head :001 > Student.create school_id: School.first.id, 'books_attributes' => {'1' => {'name' => 'I am a book'}}
ruby-1.9.2-head :002 > Student.count
MONGODB xxx_development['$cmd'].find({"count"=>"students", "query"=>{}, "fields"=>nil})
=> 2
ruby-1.9.2-head :004 > Student.all.to_a
MONGODB xxx_development['students'].find({})
=> [#<Student _id: 4f62a8341d41c81bc6000002, _type: nil, created_at: 2012-03-16 02:40:52 UTC, updated_at: 2012-03-16 02:40:52 UTC, school_id: BSON::ObjectId('4f62a8341d41c81bc6000001')>, #<Student _id: 4f62a8341d41c81bc6000003, _type: nil, created_at: 2012-03-16 02:40:52 UTC, updated_at: 2012-03-16 02:40:52 UTC, school_id: nil>]
ruby-1.9.2-head :005 > Book.count
MONGODB xxx_development['$cmd'].find({"count"=>"books", "query"=>{}, "fields"=>nil})
=> 2
ruby-1.9.2-head :006 > Book.all.to_a
MONGODB xxx_development['books'].find({})
=> [#<Book _id: 4f62a8341d41c81bc6000003, _type: nil, created_at: 2012-03-16 02:40:52 UTC, updated_at: 2012-03-16 02:40:52 UTC, name: "I am a book", student_id: BSON::ObjectId('4f62a8341d41c81bc6000002')>, #<Book _id: 4f62a8341d41c81bc6000002, _type: nil, created_at: 2012-03-16 02:40:52 UTC, updated_at: 2012-03-16 02:40:52 UTC, name: nil, student_id: nil>]
このバグは本当に私を夢中にさせます。本の検証メソッドで「学校」を呼び出すときに追加のモデルがあるのはなぜですか?
または私が間違ったことはありますか?