Form_form与Simple_form(集合:value_method,label_method)

时间:2019-06-14 11:55:47

标签: ruby-on-rails ruby simple-form form-for ruby-on-rails-5.2

在simple_form中,您可以像下面这样使用label_method和value_method。

f.association :company, collection: Company.all.order(:name), label_method: :name, value_method: :value

1)form_for是否具有相同的方法?

2)SimpleForm中的:label_method和:value_method的默认值是什么?

解决方案(在初始化程序中设置):

config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
config.collection_value_methods = [ :id, :to_s ]

1 个答案:

答案 0 :(得分:0)

是的,默认的FormBuilder具有相同的功能:

<%= form_for @yourmodel do |f| %>
  <%= f.collection_select :company_id, Company.all.order(:name), :id, :name %>
  <%= f.submit %>
<% end %>

根据collection_select helper documentation

  

collection_select (方法,集合,value_method,text_method,   options = {},html_options = {})公共

# File actionview/lib/action_view/helpers/form_options_helper.rb, line 834
def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
    @template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_html_options.merge(html_options))
end