In Ruby on Rails, an attr_accessor
is a method that allows you to define getter and setter methods for an object’s instance variables. This means that you can read and write the value of the instance variable from outside the object, just like you would with a regular variable.
Here is an example of how you might use attr_accessor
in a Rails model:
Copy codeclass User < ApplicationRecord
attr_accessor :first_name, :last_name
end
In this example, the attr_accessor
method creates getter and setter methods for the first_name
and last_name
instance variables. This means that you can use the first_name
and last_name
methods to read and write the values of these instance variables.
For example, you can use the first_name
method to get the value of the first_name
instance variable, like this:
Copy codeuser = User.new
user.first_name
You can also use the first_name=
method to set the value of the first_name
instance variable, like this:
Copy codeuser = User.new
user.first_name = "John"
The attr_accessor
method is a convenient way to create getter and setter methods for an object’s instance variables, which can make it easier to work with the object’s data.
I hope this helps! Let me know if you have any other questions.