开发者

MongoDB help (relationships)

开发者 https://www.devze.com 2023-01-25 00:42 出处:网络
I have a class Foo with an embedded objec开发者_JAVA百科t Bar. Every time a Foo is created, I want its Bar to be created. Bar is initiated by passing variables from Foo. How can I accomplish this?

I have a class Foo with an embedded objec开发者_JAVA百科t Bar. Every time a Foo is created, I want its Bar to be created. Bar is initiated by passing variables from Foo. How can I accomplish this?

Thanks


Use a before_create hook to auto create your Bar. something like

class Foo
  include Mongo....
  attr_reader :new_bar
  before_create :create_bar

  def create_bar
    self.bars << new_bar
  end
end

That way you can still validate the bar (using new_bar or whatever you want).

Both MongoMapper and Mongoid have the before_create hook, so you should be fine in either.

0

精彩评论

暂无评论...
验证码 换一张
取 消