[英]prompt option not working with select_tag
如果marital_status中有值,则不应显示提示,但以我为例。 我的代码在下面提到。 请帮忙。
= select_tag( 'request[marital_status]',
options_for_select(marital_status_options,
@employee.marital_status.try(:upcase)), prompt: "Select Marital Status", id: 'employee_marital_status', disabled: @request.submitted?)
在employee_helper.rb中
def marital_status_options
Employee::MaritalStatus::ALL.zip(Employee::MaritalStatus::ALL)
end
在员工模型中
module MaritalStatus
MARRIED = 'MARRIED'
SINGLE = 'SINGLE'
DIVORCED = 'DIVORCED'
ALL = [MARRIED, SINGLE, DIVORCED]
end
格式和用法正确。 请验证@employee.marital_status.try(:upcase)
与此处提供的marital_status_options
之一完全匹配。
看起来很可能是这种行为。
另外,select_tag中期望的第一个参数需要采用适当的格式,在这种情况下,必须是字符串数组。
因此,您的方法marital_status_options
应该返回一个用于下拉菜单的选项数组。
def marital_status_options
['MARRIED', 'SINGLE', 'DIVORCED']
end
你很亲密 这里的问题可能是由于您的marital_status_options
方法引起的:由于您的赋值,这将返回DIVORCED
因为它求值到最后一行。
因此,如果您的实例包含“ DIVORCED”,则您可能会发现该值已被选择,尽管其他两个值都不是; 您实例的值需要匹配其中之一才能被选中,而不是提示。
您可能要更改此设置:
def marital_status_options
MARRIED = 'MARRIED' # this will be evaluated first
SINGLE = 'SINGLE' # then this
DIVORCED = 'DIVORCED' # finally, this will be evaluated and returned as 'DIVORCED'
end
对于数组,可以:
def marital_status_options
['MARRIED', 'SINGLE', 'DIVORCED']
end
或者,将选项显示为小写但在数据库中保留大写值:
def marital_status_options
[['Married', 'MARRIED'], ['Single', 'SINGLE'], ['Divorced', 'DIVORCED']]
end
看一下options_for_select
上的文档,您会看到可以设置的人。
再往下看,您可能要考虑切换到enums
-这些enums
对于管理诸如此类的选择非常方便,并且可以自动生成诸如Employee.married
, employee.divorced?
等等。
正如其他人提到的,最佳做法是将这样的数据存储在相关模型中,尽管我认为这些数据应存储为常量,因为它们不会改变。 因此,以下之一:
# employee.rb
MARITAL_STATUSES = ['MARRIED', 'SINGLE', 'DIVORCED'].freeze
# or
MARITAL_STATUSES = [['Married', 'MARRIED'], ['Single', 'SINGLE'], ['Divorced', 'DIVORCED']].freeze
= select_tag('request[marital_status]',
options_for_select(Employee::MARITAL_STATUSES,
@employee.marital_status.try(:upcase)),
prompt: "Select Marital Status",
id: 'employee_marital_status',
disabled: @request.submitted?)
希望对您有所帮助-如果您有任何疑问或需要其他帮助,请告诉我。
= select_tag "request[marital_status]", options_for_select(Employee.marital_status_options,
@employee.marital_status.try(:upcase)), :include_blank => '--Select Marital Status--', id: id: 'employee_marital_status', disabled: @request.submitted?
在模型中定义marital_status_options(业务逻辑)是一个好习惯:-
假设它是员工模型
def self.marital_status_options
[
["MARRIED","MARRIED"],
["SINGLE","SINGLE"],
["DIVORCED", "DIVORCED"]
]
end
之所以没有选择默认的marital_status,是因为如果@employee.marital_status.try(:upcase)
与任何marital_status_options
不匹配,它将显示您的prompt
选项,因此请仔细检查是否@employee.marital_status.try(:upcase)
匹配选择标记选项的任何给定选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.