mmr
mmr

Reputation: 14919

How can I get a ruby on rails select dropdown to automatically contain the proper information?

I have an object called a device that is associated with a customer. Once the customer orders a device, then the factory assigns the device to the customer, and the customer registers the device, and communication between the device and the rest of its associated functions can begin.

When I display the edit page to the factory administrator via the following:

  <%= form_for @device do |f| %>
    <%= render 'fields', f: f %>

The 'customer' field, which is itself defined in its own table, appears properly as a select dropdown. However, the default value for that select is not the currently assigned customer, but is just the current customer in the list. Is there a way using the above default rendering scheme to make the select dropdown use the current value for the device?

I've tried several variations on the theme:

  <%= form_for @device do |f| %>
    <%= render 'fields', f: f %>
    <%= f.select :customer, options_for_select(@customers.each{|p| [p.name, p.id]}, @device.customer.name)%>

but these approaches just result in one gigantic dropdown that runs the entire width of the screen and, even then, does not show the appropriate default value. In addition, the f.select just shows the object ID of the customer, rather than the name itself.

Upvotes: 1

Views: 1453

Answers (1)

cortex
cortex

Reputation: 5226

From Rails api doc:

Given a container where the elements respond to first and last (such as a two-element array), the “lasts” serve as option values and the “firsts” as option text... If selected is specified, the matching “last” or element will get the selected option-tag.

According to this:

<%= f.select :customer, options_for_select(@customers.map{|p| [p.name, p.id]}, @device.customer.id)%>

You have to set the selected option to the id (the "last" of your array [name, id]): @device.customer.id and use map.

Hope this helps!

Upvotes: 1

Related Questions