Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • attr_accessor and attr_accessible methods in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 654
    Comment on it

    As we know a class can have any number of objects and each object is different from one another. The thing that distinguish one object from another is the attributes they have. So in order to write and read these attributes we have some methods in Rails.These methods are called attribute accessors.

    In this blog, I am going to explain about attr_accessor and attr_accessible.
    attr_accessor is used when we do not have a column in our database, but still, want to show a field in the form. This field is called "virtual attribute" in a Rails model. That means when we want to show some attributes without storing its value in the database then we can use attr_accessor.

    Suppose we have a Model called user in out database with following fields,

     

    • name
    • email
    • password_hash
    • password_salt

     

    Now in a console we will create an object users table and try to access password
     

    user = User.new
    user.password

     

    It Will give an error as there is no column as password in database, So to access this attribute we need to define it like this:

    class User < ActiveRecord::Base
    
      attr_accessor :password
    
    end

    Now if we try to access the password attribute, it won't give any error.
    attr_accessor will create two methods one is getter method and other is setter method.
    getter method is used to retrieve the value of the attribute and setter method is used to set the value to the attribute

     

    Another method is attr_accessible . It is used to define a whitelist of attributes of the model that can be mass assigned. So let's assume, if you have five attributes but only whitelist three of them, then only those three can be mass assigned.

    class User < ActiveRecord::Base
      attr_accessible :first_name, :last_name
    end
    
    #Now this will work fine:
    user.new({:first_name => "joe", :last_name => "paul"})
    
    #Now if you do this:
    user.new({:first_name => "joe", :last_name => "paul", :email => "paul@gmail.com"})
    #User's email attribute would not be set

    Another difference between attr_accessible and attr_accessor is that attr_accessible white lists those attributes that already exist in in model.

 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: