ruby on rails - Access to parent from embedded document on creation (Mongoid) -


this trick works "has_many" relation, fails "embeds_many". ideas?

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' nil:nilclass 

so, fails on line "field :full_name, type: string, default: ->{ "#{name}, #{country.name}" }" becouse country undefined moment

you need check country first, return country.name

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

i not work string interpolation, append works (which concatenates country.name str)


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -