3

此技巧适用于“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}" }" 行失败,因为当时国家尚未定义

4

1 回答 1

0

你需要先检查country,然后它会返回country.name

field :full_name, type: String, default: ->{ "#{name}, " << country.name if country }

我无法让它与字符串插值一起使用,但附加工作(将 country.name 连接到 str)

于 2013-04-14T04:05:32.870 回答