此技巧适用于“has_many”关系,但适用于“embeds_many”。有任何想法吗?
class Country
include Mongoid::Document
field :name, type: String
embeds_many :cities
end
class City
include Mongoid::Document
field :name, type: String
field :full_name, type: String, default: ->{ "#{name}, #{country.name}" }
embedded_in :country
end
1.9.3p392 :025 > c = Country.find_or_create_by(name: 'foo')
=> #<Country _id: foo, name: "foo">
1.9.3p392 :026 > c.cities.find_or_create_by(name: 'bar')
NoMethodError: undefined method `city' for nil:NilClass
因此,它在“field :full_name, type: String, default: ->{ "#{name}, #{country.name}" }" 行失败,因为当时国家尚未定义