Rails表单选择下拉列表显示存储在数据库中的值

时间:2017-08-25 18:45:18

标签: ruby-on-rails forms dropdown

我有一个帮助我们的状态名称和缩写,并在编辑配置文件视图中成功使用此表单,以在下拉列表中呈现状态,并在用户选择并提交表单时将状态保存到数据库。

<%= f.label :State %>
  <%= f.select(:state, options_for_select(us_states), :include_blank => "Please Select") %>

一旦我的表单保存并重新加载,即使状态保存到数据库,表单仍显示“请选择”,所以我试过这个:

  <%= f.label :State %>
      <%= f.select(:state, options_for_select(us_states), selected: @clinician_profile.state) %>

但是它显示了辅助数组(Alabama)中的第一个状态而不是保存状态。

如果数据库中没有值但是一旦用户选择了状态后显示相应的状态,我怎么能显示“请选择”?

感谢您的帮助! 这是我表格的最顶层:

<%= form_for(@clinician_profile) do |f| %>
    <%= render 'shared/error_messages', object: f.object %>

这是我的控制器:

class ClinicianProfilesController < ApplicationController
def edit
    @clinician_profile = current_user.clinician_profile
end

def index
end

def show

end

def create
end

def update
@clinician_profile = current_user.clinician_profile 
if @clinician_profile.update_attributes(clinician_profile_params)
    flash[:success] = "Profile Updated"
    redirect_to edit_clinician_profile_path(current_user)
else
    render 'edit'
    end
end


private

        def clinician_profile_params
            params.require(:clinician_profile).permit(:address1, :address2, :city, :state, :zip, 
                :accepting_patients, :rate, :license_number, :license_state, :years_licensed, :years_practicing, 
                :school, :year_graduated, :accepts_insurance, :sliding_scale, :bio, :website, insurance_ids: [], race_ids: [], language_ids: [])

end
end

2 个答案:

答案 0 :(得分:1)

问题在于options_for_selectselect一起使用时,selected选项应作为options_for_select的参数包含在内。另外,您应该使用prompt而不是include_blank所以您的代码应如下所示

<%= f.select(:state, options_for_select(us_states, selected: @clinician_profile.state), prompt: "Please Select") %>

答案 1 :(得分:-1)

options_for_select有两个参数(http://www.jooq.org/doc/latest/manual/sql-building/names),默认情况下第二个参数为nil

您需要将所选状态的值作为options_for_select(us_states, selected: @clinician_profile.state的第二个参数传递。