开发者

How to add user defined attribute to a model

开发者 https://www.devze.com 2023-01-30 05:22 出处:网络
I\'m adding \":foo\" att开发者_高级运维ribute to my user model as: attr_accessor :foo attr_accessible :foo

I'm adding ":foo" att开发者_高级运维ribute 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


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"


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

0

精彩评论

暂无评论...
验证码 换一张
取 消