29

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.

4 Answers 4

63

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

3
  • Works after I delete the extra "collection:", except that it adds a blank which I don't want. Commented Jul 21, 2013 at 15:46
  • @markhorrocks There is an options called include_blank => false just add it
    – Viren
    Commented Jul 22, 2013 at 8:30
  • @markhorrocks Edited the answer with include_blank => false options
    – Viren
    Commented Jul 22, 2013 at 8:31
7

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 %>
0
2

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.

4
  • There is such an association but @locations = Location.where(club_id: club_id), however, that looks like it may still work? Commented Jul 17, 2013 at 15:46
  • If you dont have a proper association than: <%= f.input :location, collection: @locations %>
    – Rails Guy
    Commented Jul 17, 2013 at 18:20
  • The association is defined in both the models but it produced some kind of hash for Location without an error. The rails form helper works fine. Commented Jul 17, 2013 at 18:34
  • Thank you! This was just what I was looking for. A way to have a custom collection but still send the nested fields for the association in the correct format. Commented Oct 31, 2017 at 20:55
-1

In your location model, you can also create a :

def to_label
  location_name
end
1
  • to_label is a view/display responsibility and shouldn't be defined in your model (which should only have business logic and DB concerns). Commented Jan 21, 2019 at 10:26

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.