$ rails -v
Rails 3.1.1
$ ruby -v
ruby 1.9.2p312 (2011-08-11 revision 32926) [i686-linux]
如果您想重现问题,请关注我:
首先,创建这三个模型(只是复制):
#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_many books' 关系设置为 '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>]
这个错误真的让我发疯。为什么在书籍验证方法中调用“学校”时会有其他模型?
还是我做错了什么?