Rails 4 simple_form collection_select

泪湿孤枕 提交于 2019-12-08 23:09:30

问题


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.


回答1:


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




回答2:


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



回答3:


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:


In your location model, you can also create a :

def to_label
  location_name
end


来源:https://stackoverflow.com/questions/17702426/rails-4-simple-form-collection-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!