这个技巧适用于“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: - &gt; {”#{name},#{country.name}“}”因为那个时刻国家未定义
答案 0 :(得分:0)
您需要先检查country
,然后它会返回country.name
field :full_name, type: String, default: ->{ "#{name}, " << country.name if country }
我无法使用字符串插值,但附加工作(将country.name连接到str)