edit a collection item in _form for the parent

19 views
Skip to first unread message

sheamus

unread,
Jun 29, 2012, 5:02:52 PM6/29/12
to rubyonra...@googlegroups.com
Say I have a Dog that has_may legs (In this case we don't care how many).  In the _form for Dog, I would like to assign a pre-existing let to him.  I would like to do something like this:

<%= f.collection_select :leg_1, Leg.select { |l| l.dog_id == nil }, :id, :description %>
<%= f.collection_select :leg_2, Leg.select { |l| l.dog_id == nil }, :id, :description %>

Then in my controller's create action:

@dog = Dog.new(params[:dog])
@dog.save
leg = Leg.find(params[:leg_1])
leg.dog = @dog
leg.save

The problem is that the collection_select is trying to set the leg_1 value as part of Dog, which of course does not exist. Do I need to create 'view model' for doing this?

Thanks,
~S

sheamus

unread,
Jun 30, 2012, 7:19:46 PM6/30/12
to rubyonra...@googlegroups.com
Could this be done with fields_for?

sheamus

unread,
Jul 1, 2012, 11:39:14 AM7/1/12
to rubyonra...@googlegroups.com
Thank. Yeah, I basically ended up doing something similar.  I use 'leg[]' in my select tag, and then manually hooked things up in the back end.... I wonder if in your solution if things would have been connected for me? Never mind just tried it, I still have to hook things up manually in the backend.  

Thanks for the help, good to know that I am not crazy.

Andrew Ferk

unread,
Jul 1, 2012, 2:04:09 PM7/1/12
to rubyonra...@googlegroups.com
S,

You should not have to do any manual association. If you have params[:dog][:leg_ids] = [...], it should work; you may need to set attr_accessible :leg_ids in your Dog model. Show your solution, and maybe we can refactor it to use less code.
--
Andrew Ferk
Message has been deleted

sheamus

unread,
Jul 1, 2012, 5:42:38 PM7/1/12
to rubyonra...@googlegroups.com
Ahhh, got it working as you said now. Great thanks.
Reply all
Reply to author
Forward
0 new messages