Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Bitmask Attributes in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.63k
    Comment on it

    Sometimes we need to store several booleans to determine a user's settings.Bitmask is a good solution for that.Bitmask use a single integer where each bit represents one such boolean.
    For example user has many roles.One solution would be create a text column called roles in roles table and make a one to many relationship between users and roles table.This approach works fine but if we want users to assign many roles without any roles table then we use Bitmask
    Using  bitmask we can store multiple values in a single integer column and we can retrieve users by their roles.

    To use Bitmask attributes in Rails application first we need to install below ruby gem

    gem 'bitmask_attributes'

    Now we have an integer column roles in users table. In User model we define a bitmask with its possible values.

    class User < ActiveRecord::Base
      bitmask :roles, :as => [:admin, :superadmin, :tester], :zero_value => :none
    end


    You can then modify the column using the declared values without resorting to manual bitmasks.

    user = User.create(:name => "Bruce", :roles => [:superadmin, :tester]), :zero_value => :none
    user.roles
    # => [:superadmin, :tester]

    To find ou a record with a given value:

    user.roles?(:admin)
    # => true

    To get the list of all values for any given attribute:

    User.values_for_roles
    # => [:admin, :superadmin, :tester]

    Some named scopes are also generated with `bitmask`:

    User.with_roles

    User.with_roles(:tester)

    User.with_roles(:superadmin, :tester)

    User.with_any_roles(:superadmin, :tester)

    User.with_exact_roles(:tester)

    User.with_exact_roles(:admin, :tester)

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: