简体   繁体   English

Rails布尔值-True和False与1和0

[英]Rails booleans - True and False vs 1 and 0

I recently added a new 'submitted' attribute to a Comment model in a project I'm working on. 我最近在我正在处理的项目中为Comment模型添加了一个新的“ submitted”属性。 In the migration, I created the column like this: add_column :comments, :submitted, :boolean . 在迁移中,我创建了这样的列: add_column :comments, :submitted, :boolean Note: I'm using MySQL for the database. 注意:我正在使用MySQL作为数据库。

I wanted this attribute to have a default value of false , so I added a before_create method as such: 我希望此属性的默认值为false ,因此我添加了一个before_create方法,如下所示:

before_create :default_values

def default_values
  self.submitted = false
end

This seemed correct to me, but whenever I would try and add a new comment, nothing would happen and the console would show errors. 这对我来说似乎是正确的,但是每当我尝试添加新注释时,都不会发生任何事情,并且控制台会显示错误。 My create method is done via AJAX, and the controller correctly processed the method by JS, but for some reason it was defaulting to the format html and trying to redirect to a different page. 我的create方法是通过AJAX完成的,控制器通过JS正确地处理了该方法,但是由于某种原因,它默认使用format html并试图重定向到另一个页面。

After a bit of playing around, I changed my default_values method to look like this: 经过一番试验之后,我将default_values方法更改为如下所示:

def default_values
  self.submitted = 0
end

Everything worked fine after that. 在那之后一切正常。 Does this have something to do with Rails using tinyint for a boolean field in the database? 这与Rails将tinyint用于数据库中的布尔字段有关吗? I would have thought it would be smart enough to make the conversion between false/true and 1/0. 我本以为可以在false / true和1/0之间进行转换,这足够聪明。

Interesting to note, I tried to create a new comment through the console and was able to set my submitted attribute to false with no issues. 有趣的是,我尝试通过控制台创建一个新注释,并且能够将submitted属性设置为false ,没有任何问题。 Is there a reason why I have to use an integer instead of a true/false value? 为什么我必须使用整数而不是true / false值?

It is smart about booleans, just use: 布尔值很聪明,只需使用:

object.submitted?

as the access method... 作为访问方法...

为您的迁移添加默认值:

add_column :comments, :submitted, :boolean, :default => false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM