Re: [mongoid] recursively_embeds_many example needed

305 views
Skip to first unread message

Durran Jordan

unread,
Jul 3, 2012, 6:46:43 AM7/3/12
to mon...@googlegroups.com
You don't need any second model, just add the macro, and remove the parent field:

class Musicstyle
  include Mongoid::Document
  field :musicstyle, type: String
  recursively_embeds_many
end

However there won't be any auto-setting of the parent since we're in an embedded situation, so your controller or model needs to set it... So if this was you creating a new
music style then the create action might look like:

parent = Musicstyle.find(params[:musicstyle].delete(:parent))
parent.child_musicstyles.create(params[:musicstyle])

You can see in the source, the macro is a convenience for an embeds_many/embedded_in pair:

https://github.com/mongoid/mongoid/blob/master/lib/mongoid/relations/cyclic.rb#L16



2012/7/3 Jan Jezek <global...@gmail.com>
Hi there,

sitting now since hours to figure out how to use the "recursively_embeds_many" function.

Do I need a second model like musicstyle_tree?

I am quite new to mongoid (and also rails).

My model looks like this.

class Musicstyle
  include Mongoid::Document

  field :musicstyle, type: String
  field :parent

end

my form contains this:

    <div class="field">
        <%= f.label :parent %>
        <%= f.select :parent,
                     Musicstyle.all.map { |m| [m.musicstyle, m._id] },
                     {:include_blank => "Select a parent (if needed)"} %>
    </div>

Is this the right approach?

Please help me!

many thanks

Message has been deleted

Jan Jezek

unread,
Jul 4, 2012, 10:28:38 AM7/4/12
to mon...@googlegroups.com
I (think) I got it working now:

MODEL

class Musicstyle
  include Mongoid::Document
 field :title, type: String
  recursively_embeds_many
end

CONTROLLER
def new
    @musicstyle = Musicstyle.new
    @all_musicstyles = Musicstyle.all
end
def create
    if params[:musicstyle][:parent_musicstyle]
      parent = Musicstyle.find(params[:musicstyle].delete(:parent_musicstyle))
      parent.child_musicstyles.create(params[:musicstyle])
    end
    @musicstyle = Musicstyle.new(params[:musicstyle])
end
VIEW


   <% if @all_musicstyles %>
        <div class="field">
            <%= f.label :parent_musicstyle %>
            <%= f.collection_select( :parent_musicstyle, @all_musicstyles, :_id, :title) %>
        </div>
    <% end %>

Results: (see attached screenshot)
- House
-- Ibiza House
- Ibiza House
-- Child Progressive House
- Progressive House 


hope this helps someone...

regards
:-)

Jan Jezek

unread,
Jul 4, 2012, 1:23:04 PM7/4/12
to mon...@googlegroups.com
erm, I am not really got it working... 

I got a 

undefined method `reflect_on_association' for "4ff47aff34257be005000006":String

error


Sorry Mate, please help me out!
(working since 2 days now on that "simple thing", maybe I am got blind)

Reply all
Reply to author
Forward
0 new messages