无法获取HTML选择表单以显示用户先前保存到数据库的选定home_state

时间:2019-02-28 18:47:47

标签: html ruby-on-rails ruby devise

当用户选择任何状态并保存然后重新加载时,它仅返回第一个状态,即阿拉巴马州。我通过Rails控制台检查了数据库,以确认它是否正确保存并且确实保存了,但是HTML选择不仅获得了正确的字段。其他字段接收的值正确。

这是_contact_info.html.erb

<div class="form-group col-md-4">
 <%= f.select :home_state, options_for_select(us_states), id: "home_state",
  prompt: "State", class: "form-control" %>
</div>

Application_controller.rb

<div class="form-group col-md-4">
      <%= f.select :home_state, options_for_select(us_states), id: "home_state",
      prompt: "State", class: "form-control" %>
    </div

us_states.helper

模块UsStatesHelper

    def us_states
        [
          ['Alabama', 'AL'],
          ['Alaska', 'AK'],
          ['Arizona', 'AZ'],
          ['Arkansas', 'AR'],
          ['California', 'CA'],
          ['Colorado', 'CO'],
          ['Connecticut', 'CT'],
          ['Delaware', 'DE'],
          ['District of Columbia', 'DC'],
          ['Florida', 'FL'],
          ['Georgia', 'GA'],
          ['Hawaii', 'HI'],
          ['Idaho', 'ID'],
          ['Illinois', 'IL'],
          ['Indiana', 'IN'],
          ['Iowa', 'IA'],
          ['Kansas', 'KS'],
          ['Kentucky', 'KY'],
          ['Louisiana', 'LA'],
          ['Maine', 'ME'],
          ['Maryland', 'MD'],
          ['Massachusetts', 'MA'],
          ['Michigan', 'MI'],
          ['Minnesota', 'MN'],
          ['Mississippi', 'MS'],
          ['Missouri', 'MO'],
          ['Montana', 'MT'],
          ['Nebraska', 'NE'],
          ['Nevada', 'NV'],
          ['New Hampshire', 'NH'],
          ['New Jersey', 'NJ'],
          ['New Mexico', 'NM'],
          ['New York', 'NY'],
          ['North Carolina', 'NC'],
          ['North Dakota', 'ND'],
          ['Ohio', 'OH'],
          ['Oklahoma', 'OK'],
          ['Oregon', 'OR'],
          ['Pennsylvania', 'PA'],
          ['Puerto Rico', 'PR'],
          ['Rhode Island', 'RI'],
          ['South Carolina', 'SC'],
          ['South Dakota', 'SD'],
      ['Tennessee', 'TN'],
      ['Texas', 'TX'],
      ['Utah', 'UT'],
      ['Vermont', 'VT'],
      ['Virginia', 'VA'],
      ['Washington', 'WA'],
      ['West Virginia', 'WV'],
      ['Wisconsin', 'WI'],
      ['Wyoming', 'WY']
    ]   end

结束

1 个答案:

答案 0 :(得分:0)

您需要传入要开始选择的元素的值。像

<div class="form-group col-md-4">
 <%= f.select :home_state, options_for_select(us_states, selected_state.abbreviation), id: "home_state",
  prompt: "State", class: "form-control" %>
</div>

有关更多详细信息,请参见https://guides.rubyonrails.org/form_helpers.html#the-select-and-option-tags