将默认值设置为f.select不能按要求工作

时间:2014-07-04 14:00:48

标签: ruby-on-rails simple-form

我有一个像这样下拉的简单表单,我正在为它设置默认值。

= simple_form_for :"#{filter.underscore_field_name}",:url=> admin_requests_path,:method => "get",html: {:"data-filter"=>"#{filter.underscore_field_name}"}  do |f|
    = f.select("#{filter.name}", options_for_select(filter.filter_values.all.collect {|p| [ p.name, p.id ] },default_filter_value_id_det(request,filter)),{:include_blank => "None specified"},{class: "form-control chosen-select select_tag_filter",data: {"field_name"=>"#{filter.underscore_field_name}"}})

我正在使用助手找到默认值。

def default_filter_value_id_det(request,filter)
    af = request.filter_value_requests.find_by(admin_filter: filter)
    if af
        af.admin_filter_value.id
    else 
        nil
    end
end

af出现时选择正确的值但条件为nil时,它仍然将下拉列表设置为第一个值而不是正确的值。这是为什么?

1 个答案:

答案 0 :(得分:0)

try this

def default_filter_value_id_det(request,filter)
af = request.filter_value_requests.find_by(admin_filter: filter)
if af
    af.admin_filter_value.id
else 
    ""
end
end

或只是

  def default_filter_value_id_det(request,filter)
      af = request.filter_value_requests.find_by(admin_filter: filter)
      af.nil? ? '' :  af.admin_filter_value.id
  end