Is there a way to specify something like accept_nested attributes_for
for embedded documents, and easy design a Nested Document Form as in
ActiveRecord?
Anybody knows if thIs this planned for the future?
Thanks
> --
> You received this message because you are subscribed to the Google
> Groups "MongoMapper" group.
> For more options, visit this group at
> http://groups.google.com/group/mongomapper?hl=en?hl=en
On Jan 12, 2010, at 6:11 AM, jmcervera <juanma...@gmail.com> wrote:
If anyone has a good generic solution for handling a document and many
embedded documents in a single form, though, I'd really like to see
it. I've been hacking around it in my controllers, and it's been very
ugly.
def accepts_nested_attributes_for(*args)
arg = *args.pop
target_model = arg.to_s.classify
is_many = !arg.to_s.grep(/[^s]s$/).empty?
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{arg}_attributes
instance_variable_get("@#{arg}_attributes")
end
def #{arg}_attributes=(value)
new_value = []
value.each {|key, attrs|
new_value << #{target_model}.new(attrs)
}
new_value = new_value.first unless #{is_many}
send("#{arg}=", new_value)
end
RUBY
accepts_nested_attributes_for(*args) unless args.empty?
end
A warning though: if you mark a related document for destruction (by
assigning "_destroy" => true), it will be destroyed even if the
document is not saved. This is only for associated documents (not
embedded docs). I have an idea of how to change this, but it will take
some more work to get there.
Feel free to use if you want, but no guarantees... Tests aren't
complete (and one is failing now), but that's why I haven't released
this publicly yet.
Hope this helps!
Based in what you've done, I have ported the activerecord version
https://gist.github.com/d313817a57fd079e4df7
It works pretty well for me, I include MongoMapper::NestedAttributes
in every Document and EmbeddedDocument that need nested attributes.
I think it would be nice that something like this will be merged in
MongoMapper and have the functionality already included.
Juanma
I'd really like to see this in MongoMapper core as well.
Thanks a lot!
But somehow @parent.update_attributes(params[:parent-with-embedde-
docs] doesn't work....
It works for the parent object, the embedded-documents get updated
too, but every value that isn't sent with the form is overrridden with
nil....
But creating a new Record like this works...
Maybe somebody else has an idea.
Regards,
Manuel
Is update_attributes designed to also update embedded_documents?
Or do I have to overwrite update_attributes or use the patch from
Juanma?
I just thought that this works without a patch, because the creation
of a new record works perfect...
I use the latest master branch.
Thanks for every hint :-)