Topic: attr_accessor woes

Hi everyone,

I must be doing something wrong (or maybe I don't understand when I'd want to be able to use attr_accessor).

I'm working on a user/authentication system.  I've got a User model in user.rb, set up with validations and such.

class User < ActiveRecord::Base

  validates_presence_of :username,
  validates_presence_of :password, :on => :create
  validates_presence_of :password_confirmation, :on => :create
  validates_uniqueness_of :username
  validates_length_of :password,
                      :minimum => 6,
                      :message => "must be at least 6 characters long.",
                      :on => :create
  attr_accessor :password_confirmation, :active
  attr_reader :password
  validates_confirmation_of :password

  #remainder snipped for brevity.

What I want to do, in my login action, is check to see if the user is active before setting the session[:user_id] variable.  With the code as written above, any time I create a new user, even specifying :active => true in the create statement, my user details always show active as 'false'.  If I set it manually via = true, it doesn't make the change.

Is this the wrong time to be using attr_accessor :active?  If I take that out, the create works as expected.


Re: attr_accessor woes

Is "active" a column in the users table? If so, you don't need to set attr_accessor because ActiveRecord automatically creates the getter/setter methods for that.

This might explain something:

class User < ActiveRecord::Base

  attr_accessor :active
  # is the same as typing ....
  def active=(active)
    @active = active

  def active

But, as I said, you don't need to do that if it's a column in the database.

Railscasts - Free Ruby on Rails Screencasts

Re: attr_accessor woes

:active is indeed a column in the users table.  Wow, in all the tutorials, I never encountered an explanation that the attr_accessor (and it's cousins attr_reader and attr_writer) are only necessary for Object/Instance variables which aren't stored in the database. 

I did understand how the attr_accessor method takes the place of writing the get/set methods, I just had no idea that even that was redundant for fields stored in the database.

Thanks Ryan!