jcandia2
jcandia2

Reputation: 1

How to create a simple form select input from an array of hashes

I'm using the simple form gem and I am having a hard time creating a select input and options for an object's attribute. End result should be like:

<select name="sales_invoice[flooring_company_name]" id="sales_invoice_flooring_company_name">
  <option value=""></option>
  <option value="XL Funding">XL Funding - 11111111</option>
  <option value="AFC">AFC - xxxxx</option>
  <option value="Ally">Ally -</option>
</select>

In my controller I have:

@payment_preferences = [{:name=>"XL Funding", :account_number=>"11111111"}, {:name=>"AFC", :account_number=>"xxxxx"}, {:name=>"Ally", :account_number=>""}]

In my html.erb I have tried:

<%= f.input :flooring_company_name, label: false, collection: @payment_preferences, :label_method => :name, :value_method => :name, include_blank: true %>

Which results in error: NoMethodError - undefined method `name' for "XL FUNDING":String

So i tried:

<%= f.input :flooring_company_name, label: false, collection: @payment_preferences, :label_method => :first, :value_method => :first, include_blank: true %>

Results in:

<select name="sales_invoice[flooring_company_name]" id="sales_invoice_flooring_company_name"> 
  <option value=""></option>
  <option value="[:name, "XL Funding"]">[:name, "XL Funding"]</option>
  <option value="[:name, "AFC"]">[:name, "AFC"]</option>
  <option value="[:name, "Ally"]">[:name, "Ally"]</option>
</select>

Upvotes: 0

Views: 1173

Answers (1)

Yan Laguna
Yan Laguna

Reputation: 11

The recommendation in simple_form gem page is to use a collection of [value:String, name:String] so I guess one solution is to change your @payment_preferences to:

@payment_preferences = [
  ["XL Funding", "XL Funding - 11111111"],
  ["AFC", "AFC - xxxxx"],
  ["Ally", "Ally - "]
];

If you really want to pass the way you are using it seems both methods you are using are lambdas, it is a bit of overengineering but you could use a lambda, check here https://stackoverflow.com/a/6334645/4507525

Upvotes: 1

Related Questions