I recently added a new 'submitted' attribute to a Comment model in a project I'm working on. In the migration, I created the column like this: add_column :comments, :submitted, :boolean
. Note: I'm using MySQL for the database.
I wanted this attribute to have a default value of false
, so I added a before_create
method as such:
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.
After a bit of playing around, I changed my default_values
method to look like this:
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? I would have thought it would be smart enough to make the conversion between false/true and 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. Is there a reason why I have to use an integer instead of a true/false value?
It is smart about booleans, just use:
object.submitted?
as the access method...
为您的迁移添加默认值:
add_column :comments, :submitted, :boolean, :default => false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.