Rails存储选择输入的键值

时间:2012-07-24 11:27:06

标签: ruby-on-rails select helper

我的.html.erb:

 <label for="form_marital_status">Marital Status:</label>
 <%= select("form", "marital_status", marital_status_options, {}, { }) %>

在我的助手中将marital_status_options定义为:

 def marital_status_options
      %w[Select Single Married Common-Law/Partner Divorced Widowed]
 end

我有没有办法定义marital_status_options以便在select中使用键值配对?

1 个答案:

答案 0 :(得分:4)

%w[Select Single Married Common-Law/Partner Divorced Widowed]

这将使每个选项的选项值和文本相同。如果希望每个选项的选项值和文本不同,则返回数组数组。每个数组中的第一个值是选项的文本值;第二个是期权价值本身。

def marital_status_options
  [["Select", ""], ["Single", "single"], ["Married", "married"], ["Common-Law/Partner", "partners"], ["Divorced", "divorced"], ["Widowed", "widowed"]] 
end

the documentation清楚解释了这一点。

您还应该考虑不从方法中传递空白"Select"选项,因为有办法通过select方法本身执行此操作。

# Helper
def marital_status_options
  [["Single", "single"], ["Married", "married"], ["Common-Law/Partner", "partners"], ["Divorced", "divorced"], ["Widowed", "widowed"]] 
end

# form
<%= select("form", "marital_status", marital_status_options, {:include_blank => "Select"}) %>