If :string is for text, how is checkbox data stored in rails?
rails g migration add_anonymous_to_开发者_如何学编程message anonymous:???
If I were adding a title etc to a message then I would put rails g migration add_title_to_message title:string
but if :anonymous is a check box in the message submit form how do I add it to the database so that there are only two options: box checked=anonymous and box unchecked=username displayed?
Thanks
Are you sure you need another database column? What you could do is
- Add a column
username:string
which allowsNULL
values (default) - Validate the model so that if
anonymous
is unchecked, saving a blank username is invalid - Validate the model so that if
anonymous
is checked, the username is always saved as blank (nil
), regardless of the form value - When you check later on whether or not a message is anonymous you simply check for
message.username.nil?
If for some reason you do need a separate DB column for anonymous
, it should look like this:
rails g migration add_anonymous_to_message anonymous:boolean
Although not all RDBMS support boolean
columns (MySQL doesn't), Rails takes care of this by generating a TINYINT(1)
or similar column when you specify boolean
, which is set to either 0
or 1
.
You have to use boolean type to store anonymous
and string to store username
:
rails g migration add_anonymous_and_username_to_message anonymous:boolean :default => false username:string
精彩评论