[英]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.