views:

19

answers:

1

I have a complex form (like Ryan B's Complex Form Railscasts) where I have a few levels of database tables being altered at the same time.

The code for this dropdown box works in that it delivers the correct integer to the database. But, despite numerous attempts I cannot get it to correctly reflect the database's CURRENT value. How can I sort out this code?

<%= o.select :weighting, options_for_select([
  ["Correct", "4", {:class=>"bold"}],
  ["Good", "3"],
  ["Average", "2"],
  ["Poor", "1"], 
  ["Incorrect", "0", {:class=>"bold"}] ], :weighting), {},
  html_options = {:class => "listBox", :style=>"float:left;"} %>

Thanks.

+1  A: 

You're on the right track, but not quite there.

While the final argument to options_for_select should be the value of the selected option. The value you supply :weighting is a symbol that does not match the value of any of your given options.

You will need to give the actual value. If you used an instance object to build the form as in

<%form_for @whatever do |o|%>
...

You can simply used @whatever.weighting.to_s as in:

<%= o.select :weighting, options_for_select([
  ["Correct", "4", {:class=>"bold"}],
  ["Good", "3"],
  ["Average", "2"],
  ["Poor", "1"], 
  ["Incorrect", "0", {:class=>"bold"}] ], @whatever.weighting.to_s), {},
  html_options = {:class => "listBox", :style=>"float:left;"} %>

Otherwise, there's a way to get the object off the form block variable o. But that's messing with internals which may change with an upgrade.

Edit: In the case where you're working with fields for and multiple partials, you can get the particular object off of the form builder block variable.with the object accessor.

Reusing the above example something like this to use the current weighting of each child instance in that instance's section of the form.

<% form_for @parent do |p| %>
  ...
  <% p.fields_for :children do |c| %>
  ...
  <%= c.select :weighting, options_for_select([
      ["Correct", "4", {:class=>"bold"}],
      ["Good", "3"],
      ["Average", "2"],
      ["Poor", "1"], 
      ["Incorrect", "0", {:class=>"bold"}] ], c.object.weighting.to_s), {},
      html_options = {:class => "listBox", :style=>"float:left;"} %>
  ...
  <% end %>
<% end %>

This can also be used in partials.

EmFi
EmFi, I do have a Ryan Bates Complex Forms 3 situation where the fields_for partials need to access their variables. For those, I have one parent and multiple children - how could I access a particular child's value?
sscirrus
I've updated the answer to address your specific need.
EmFi
You're awesome EmFi. Thank you!
sscirrus