How to show form with embedded fileds in Rails3?

53 views
Skip to first unread message

redhotberry

unread,
Jan 14, 2011, 9:04:04 AM1/14/11
to Mongoid
Hey guys! I need your help. I'm so tired with all fail attempts for
hours.
I use rails3. I have models "User" and "IM". User embedds IM.
I need to show form for creating new User with all IM's fields. How to
do that?
I have found nice solution here:
http://groups.google.com/group/mongoid/browse_thread/thread/e336576fb2c291e2/f79dca1da951cb2d
but it works if User alredy exists. I mean this solution works if i
add IM fields for existing User.
But how to create new User and at the same time add embedded IM
fields?
Please, help me!

Dulo

unread,
Jan 15, 2011, 4:02:23 PM1/15/11
to Mongoid
Models:

User
embeds_one :im
accepts_nested_attributes_for :im

IM
embedded_in :user, :inverse_of => :im

Controller:

def new
@user = User.new
@user.build_im

def create
@user = User.new(params[:user])

View:

= form_for @user do |f|
-if @user.errors.any?
#error_explanation
%h2= "#{pluralize(@user.errors.count, "error")} prohibited this
user from being saved:"
%ul
- @user.errors.full_messages.each do |msg|
%li= msg

.field
= f.label :name
= f.text_field :name
.im
= f.fields_for :im do |fim|
.field
= fim.label :name
= fim.text_field :name
.actions
= f.submit 'Save'






On 14 Sty, 15:04, redhotberry <redhotbe...@gmail.com> wrote:
> Hey guys! I need your help. I'm so tired with all fail attempts for
> hours.
> I use rails3. I have models "User" and "IM". User embedds IM.
> I need to show form for creating new User with all IM's fields. How to
> do that?
> I have found nice solution here:http://groups.google.com/group/mongoid/browse_thread/thread/e336576fb...

redhotberry

unread,
Jan 18, 2011, 3:22:39 AM1/18/11
to Mongoid
Yooooohooo, i love you!

redhotberry

unread,
Jan 18, 2011, 5:04:04 AM1/18/11
to Mongoid
It works well but what if i have embedded Document in IM model ? For
example ICQ
How to be ? Does it support deeper nesting? If yes - how to do it?
This way doesn't work:

def new
@user = User.new
@user.build_im.build_icq

Dulo

unread,
Jan 18, 2011, 9:04:58 AM1/18/11
to Mongoid
@user = User.new
@user.build_im
@user.im.build_icq

redhotberry

unread,
Jan 18, 2011, 9:13:34 AM1/18/11
to Mongoid
Thank you. And last question: all this code works only for embeds_one
but not with embeds_many?

Durran Jordan

unread,
Jan 18, 2011, 9:33:58 AM1/18/11
to mon...@googlegroups.com
Embeds many you just call #build on the association itself (instead of #build_name), since it will never be nil like an embeds_one can.

2011/1/18 redhotberry <redho...@gmail.com>

Peter Haza

unread,
Jan 18, 2011, 9:41:42 AM1/18/11
to mon...@googlegroups.com
#build is very complicated. It causes the parent to be saved, and with Mongoid::Versioning it's a minefield.
We just had to work around this 10 minutes ago.

I'm not sure what has changed in mongoid 2rc, but aparently it works better there.
Reply all
Reply to author
Forward
0 new messages