2

I am using simple_form and have an array of values stored in the model. I want the index to the stored in the table, with the value displayed on the selection drop-down.

So far I have this:

model

PRIMER_TM_FORMULA_OPTIONS = ["Breslauer et al. 1986", "SantaLucia 1998"]

form

  <%= f.input :primer_tm_formula, :collection => 0..Primer3Batch::PRIMER_TM_FORMULA_OPTIONS.length, :label_method => lambda { |i| Primer3Batch::PRIMER_TM_FORMULA_OPTIONS[i] }, label: 'Thermo Parms', input_html: {class: 'input-large'}, selected: :primer_tm_formula  %>

It's mostly working, but after an update, and when the form is refreshed, the page always displays the value at the 0 index of the array, even though the correct value is stored in the database.

Also, it seems to be this code is quite convoluted. As part of the answer, if there is a more concise way to achieve the same goal please let me know.

FINAL CODE

Based on the accepted answer, the final code in the view is this, for anyone else trying to do the same thing.

<%= f.input :primer_tm_formula,
    collection: 0..Primer3Batch::PRIMER_TM_FORMULA_OPTIONS.length,
    label_method: lambda { |i| Primer3Batch::PRIMER_TM_FORMULA_OPTIONS[i] },
    label: 'Thermo Parms',
    input_html: {class: 'input-large'},
    selected: Primer3Batch::PRIMER_TM_FORMULA_OPTIONS[f.object.primer_tm_formula] %>

1 Answer 1

2

You can get the stored value by referencing the form object: f.object.primer_tm_formula and setting it like so: selected: f.object.primer_tm_formula

7
  • Thanks for your answer, but I couldn't get it to work. Did you mean selected: f.object.primer_tm_formula (not value)
    – port5432
    Jul 6, 2013 at 16:02
  • Yes, sorry for the typo I meant primer_tm_formula Jul 6, 2013 at 16:05
  • No I am afraid it is doing the same thing - displaying the 0 index value, regardless of what is in the database.
    – port5432
    Jul 6, 2013 at 16:09
  • What is being stored in the db? You could print this and verify the correct things are stored. If you are storing theindex value use that in conjunction with your constant like so selected: Primer3Batch::PRIMER_TM_OPTIONS_FORMULA_OPTIONS[f.object.primer_tm_formula] Jul 6, 2013 at 16:29
  • No luck. I've added some text to the question. I think I will try reloading the form instance variable.
    – port5432
    Jul 6, 2013 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.