Jamal Abdul Nasir
Jamal Abdul Nasir

Reputation: 2667

How to add user defined attribute to a model

I'm adding ":foo" attribute to my user model as:

attr_accessor :foo
attr_accessible :foo

But when I set this attribute from a session controller or any other controller as:

User.foo = "my attributre"

and I get this attribute as:

User.foo

so these are not recognize and gives me an error, which is:

undefined method `foo=' for #<Class:0xb75366fc>

So please help here. I AM USING RAILS 2.3.5

Upvotes: 0

Views: 683

Answers (2)

DanneManne
DanneManne

Reputation: 21180

attr_accessor does not create a class method, it creates instance methods. So given your code, it should work to use:

@user = User.new
@user.foo = "bar"

Edit:

However, if you do want to create custom methods, then you could do something like this:

class User < ActiveRecord::Base

  def self.add_accessor(attr)
    define_method(attr) do  
      instance_variable_get("@#{attr}")
    end        

    define_method("#{attr}=") do |val| 
      instance_variable_set("@#{attr}",val)
    end
  end

And then you call it from your Controller:

User.add_accessor "foo"
@user = User.new
@user.foo = "bar"

Upvotes: 5

Raghu
Raghu

Reputation: 2563

Try this if you want to have an attribute accesor at the class level In the User model , Use this code

 class << self
      attr_accessor :foo
    end

Further reference http://apidock.com/rails/Class/cattr_accessor

Upvotes: 3

Related Questions