如何使用单选按钮将 nil 保存在数据库中
How save nil in database using radio button
我有单选按钮,我想用它来保存出勤信息:
是的,不,也许
HAML 中的代码:
= f.input :attendee, :as => :radio, :collection => { "Yes" => true, "No" => false, "Maybe" => nil }, :label => "Attendence:"
数据库中的现场参加者是布尔类型。
当我将我的值从 Yes/No 更改为 Maybe rails 时,没有将 'nil' 保存在数据库中。我应该怎么做才能节省 'nil'
如果布尔值默认设置为 true 或 false,则它不会接受空值,否则您可以按照下面的建议将空白值传递给布尔字段。
= f.input :attendee, :as => :radio, :collection => { "Yes" => true, "No" => false, "Maybe" => "" }, :label => "Attendence:"
Boolean is true/false
,你不能有nil
(nil
被视为假):
In computer science, the Boolean data type is a data type, having two values (usually denoted true and false). [[If not true, false]]
enum
你会更好:
#app/models/model.rb
class Model < ActiveRecord::Base
enum attendee: [:yes, :no, :maybe]
end
这比使用 boolean
稍微臃肿一些,但保留了 data integrity(您必须破解 Rails 布尔值才能识别 nil
如 maybe
)。 Enum
列是 integers
,每个 enum
由一个数字表示...
yes = 0
no = 1
maybe = 2
这样,您就可以执行以下操作:
= f.input :attendee, as: :radio, collection: Model.attendees, :label => "Attendence:"
我有单选按钮,我想用它来保存出勤信息: 是的,不,也许
HAML 中的代码:
= f.input :attendee, :as => :radio, :collection => { "Yes" => true, "No" => false, "Maybe" => nil }, :label => "Attendence:"
数据库中的现场参加者是布尔类型。 当我将我的值从 Yes/No 更改为 Maybe rails 时,没有将 'nil' 保存在数据库中。我应该怎么做才能节省 'nil'
如果布尔值默认设置为 true 或 false,则它不会接受空值,否则您可以按照下面的建议将空白值传递给布尔字段。
= f.input :attendee, :as => :radio, :collection => { "Yes" => true, "No" => false, "Maybe" => "" }, :label => "Attendence:"
Boolean is true/false
,你不能有nil
(nil
被视为假):
In computer science, the Boolean data type is a data type, having two values (usually denoted true and false). [[If not true, false]]
enum
你会更好:
#app/models/model.rb
class Model < ActiveRecord::Base
enum attendee: [:yes, :no, :maybe]
end
这比使用 boolean
稍微臃肿一些,但保留了 data integrity(您必须破解 Rails 布尔值才能识别 nil
如 maybe
)。 Enum
列是 integers
,每个 enum
由一个数字表示...
yes = 0
no = 1
maybe = 2
这样,您就可以执行以下操作:
= f.input :attendee, as: :radio, collection: Model.attendees, :label => "Attendence:"