usage of attr_accessor in Rails

前端 未结 5 646
不思量自难忘°
不思量自难忘° 2020-11-27 05:53

When do you use attr_reader/attr_writer/attr_accessor in Rails models?

5条回答
  •  迷失自我
    2020-11-27 06:29

    Rails models are just ruby classes that inherit from ActiveRecord::Base. ActiveRecord employs attr_accessors to define getters and setters for the column names that refer to the ruby class's table. It's important to note that this is just for persistence; the models are still just ruby classes.

    attr_accessor :foo is simply a shortcut for the following:

    def foo=(var)
      @foo = var
    end
    
    def foo
      @foo
    end
    

    attr_reader :foo is simply a shortcut for the following:

    def foo
      @foo
    end
    

    attr_writer :foo is a shortcut for the following:

    def foo=(var)
      @foo = var
    end
    

    attr_accessor is a shortcut for the getter and setter while attr_reader is the shortcut for the getter and attr_writer is a shortcut for just the setter.

    In rails, ActiveRecord uses these getters and setters in a convenient way to read and write values to the database. BUT, the database is just the persistence layer. You should be free to use attr_accessor and attr_reader as you would any other ruby class to properly compose your business logic. As you need to get and set attributes of your objects outside of what you need to persist to the database, use the attr_s accordingly.

    More info:

    http://apidock.com/ruby/Module/attr_accessor

    http://www.rubyist.net/~slagell/ruby/accessors.html

    What is attr_accessor in Ruby?

提交回复
热议问题