markhorrocks
markhorrocks

Reputation: 1398

Rails 4 simple_form collection_select

How do I translate the following to simple form?

<%= form_for(@bill) do |f| %>

<%= f.label :location_id %>
<%= f.collection_select(:location_id, @locations, :id, :location_name, 
      {:selected => @bill.location_id}) %>

I can't use a simple association because @locations is the result of a where query.

Upvotes: 29

Views: 57959

Answers (4)

Supernini
Supernini

Reputation: 591

In your location model, you can also create a :

def to_label
  location_name
end

Upvotes: -1

Viren
Viren

Reputation: 5962

Try this

<%= simple_form_for @bill do |f| %>
   <%= f.input :location,:collection => @locations,:label_method => :location_name,:value_method => :id,:label => "Location" ,:include_blank => false %>
   <%= f.button :submit %>
<%end%>

Hope this help

Upvotes: 63

markhorrocks
markhorrocks

Reputation: 1398

Here is the final:

<%= f.input :location_id, collection: @locations, label_method: :location_name, value_method: :id,label: "Location", include_blank: false, selected: @bill.location_id %>

Upvotes: 7

Rails Guy
Rails Guy

Reputation: 3866

In simple form, if we have an association between location and bill, than we can do like this:

<%= simple_form_for @bill do |f| %>
  <%= f.association :location, collection: @locations, priority: @bill.location %>
  <%= f.button :submit %>
<% end %>

Hope this will help.

Upvotes: 2

Related Questions