2

Why would you use attr_accessor in Rails?

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

My understanding is that it can be used to create "transient" variables that are not persisted in the db. And that it's a substitute for manually writing a setter and a getter.

But I don't think other answer explain much more than above. Ie: Why use Ruby's attr_accessor, attr_reader and attr_writer?

So I'm still not sure in what situation I would actually use it. Can anyone elaborate?

Community
  • 1
  • 1
tim_xyz
  • 11,573
  • 17
  • 52
  • 97

1 Answers1

0

If by "in rails" you mean "activerecord models", then your guess is correct: transient attributes.

Here's an example (a bit contrived):

class User < ActiveRecord::Base
  attr_accessor :is_admin

  validate_presence_of :name, :shipping_address, :billing_address, unless: :is_admin
end

Users created via regular flow (signup page) will refuse to get saved unless you provide all of the info. But there's a simpler flow for creating admins:

User.create(email: 'chris@example.com', is_admin: true)
# you do this in rails console or rake task, for example

Naturally, you should not accept this "private" flag from html forms (strong_params method in your controller).

Thinking a bit more about this example: you possibly want to store this flag in the database (is user admin or not). But I hope this should illustrate the idea anyway.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367