开发者

polymorphic .find_or_create_by with mongoid 2.0.1, on embedded document collections?

in previous released of Mongoid (2.0.beta.20), I could pass a class type as the 2nd parameter of the .find_or_create_by block on embedded document collections. this doesn't appear to be the case any more, with v2.0.1, yet I still need to do polymorphic find_or_create_by. any suggestions / pointers on how to do this?

I used to do this:

SomeClass.childclass.find_or_create_by({:key => "value"}, InheritingChildClas开发者_运维问答s)

now I get an exception saying too many arguments (2 for 1) on .find_or_create_by.

how can I tell the collection to create an object of the correct type, when using find_or_create_by? Or, how can i create my own method that will be functionaly equivalent to what I want, and be re-usable across my embedded document collections?

any help is appreciated.

thanks.


I ended up rolling my own solution for this

module Mongoid::Relations
  class Many
    def find_or_new(attrs, type, &block)
      inst = self.where(attrs).first

      unless inst
        inst = type.new
        inst.write_attributes attrs
        self << inst
      end

      inst
    end
  end
end


Not sure I really understood your need to inform the subclass, but check this gist: https://gist.github.com/960684

I do search subclass instances without needing to inform it. Perhaps your scenario really needs it, but if it does, why don't you call subclass's find_or_create_by?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜