Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options_for_select - how to select what's in the database?

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.

like image 326
sscirrus Avatar asked Oct 20 '10 03:10

sscirrus


1 Answers

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.

like image 93
EmFi Avatar answered Nov 19 '22 16:11

EmFi