在创建时从嵌入式文档访问父级(Mongoid)

时间:2013-04-05 18:03:27

标签: ruby-on-rails ruby activerecord mongoid

这个技巧适用于“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}“}”因为那个时刻国家未定义

1 个答案:

答案 0 :(得分:0)

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

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

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