1

我的 .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为在选择中使用键值对?

4

1 回答 1

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

这在文档中有清楚的解释。

您还应该考虑不要"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"}) %>
于 2012-07-24T11:30:48.207 回答