Ruby on Rails Development ab initio (40)-ActiveRecord Base (Boolean attribute)

Source: Internet
Author: User
Tags definition ruby on rails

Some databases support a Boolean type, while others do not, making it difficult for an active record to abstract a Boolean type. For example, if the database does not support Boolean types, some developers use char (1) Instead, and the content uses "T" and "F" to represent true and false, while others use the integer type, and 0 is false,1 true. Even if the database supports a Boolean type, you might use 0 and one storage internally.

In Ruby, both the number 0 and the character F are considered to be true values, which means that if you use the value of the attribute directly, your code is considered to be true rather than what you think is false, for example:

# Don't use it like this

user = Users.find_by_name ("Dave")
if User.superuser
grant_privileges
End

When you use attributes in a query condition, you must add a question mark after the column name:

# It's the right thing to do #

user = Users.find_by_name ("Dave")
if User.superuser?
Grant_privileges End

When you use the access operator to get the value of a property, the value is the number 0, or the character "0", "F", "false", or "" (an empty string), or nil, or a constant false, is considered false, otherwise, it is considered true.

If you are developing on a legacy system or a non-English system, the above definition of true may not work, in which case you can override the definition of the built-in predicate method, for example, in the case of Dutch, where the field may contain J or N, in which case you can do the following:

Class User < ActiveRecord::Base
def Superuser?
Self.superuser = = ' J ' End
#
... End
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.