views:

28

answers:

1

UPDATE: SOLUTION AT BOTTOM

I'm hoping someone else has spent some time ironing out this same issue... I'm building an address book within an rails application, and I have an Person model and an Email model. Person has_many Emails, and Person accepts_nested_attributes_for :emails.

This all works perfectly -- I have a nested form with which I can add and remove emails and their attributes in my form (using a method similar to Railscasts 196-7 (here)). Submitting the form creates the Person, as well as the Emails, with all the correct associations.

The problem is, as it stands, I'm unable to find a way to use a select tag on the nested email model for the user to select a KIND (e.g. work, home, other) for that email. So, editing the Person model as I have it now, there is no easy way to select the attribute that is stored in the rails model.

Here's what I have now:

<%= form_for(@source) do |f| %> 
<% f.fields_for :emails do |builder| %>  
. . . 
<%= builder.text_field :address, :size => 15 %>



<%= render :partial => 'email_select_1' %>0<%= render :partial => 'email_select_2' %>0<%= render :partial => 'email_select_3' %>

Note: the above is a hacky way of allowing me to set the ID later in javascript using the same code fragments. The partials spit out a hard-coded select and options, in this case '0' but in javascript I can change it to a unique:

<select id="person_emails_attributes_0_kind" name="person[emails_attributes][0][kind]"><option value="work">work</option><option value="home">home</option><option value="other">other</option></select>

and then the rest looks like this (abbrev):

. . .
<% end %>  
. . .
<!-- more form stuff, actions, etc... -->
. . . 
<% end %>

Is there a way to use the select_tag helper for this, and replace my hacky-hard-coded select? If not, any suggestions for writing my own helper method?

Thanks in advance!

UPDATE: Thanks to Geoff for the solution. For posterity, the big thing is to use select, not select_tag. Then you can just do something like this:

<%= builder.select :kind, [['work', 'work'], ['home', 'home'], ['other', 'other']]%>
A: 

you should just need to pass the formbuilder variable to the partial. you would do so by coding your partial like this:

<%= form_for(@source) do |f| %> 
  <% f.fields_for :emails do |builder| %>  
  . . . 
  <%= builder.text_field :address, :size => 15 %>
    <%= render :partial => 'email_select_1', :locals => {:builder => builder} %>
  <% end %>
<% end %>

And then your partial you would use:

<%= builder.select :kind %>

just as if it was within the fields_for block.

Hope this helps!

Geoff Lanotte
On testing, I'm getting this error:undefined method `select_tag' for #<ActionView::Helpers::FormBuilder:0x1343deb38>Any ideas?
Pirripli
it is builder.select sorry about that... fixed my post.
Geoff Lanotte
Great, thanks! Works perfectly.
Pirripli