TIL You Can Add Virtual Attributes to Rails Models

Andy Zhao on February 22, 2018

Disclaimer: I learned about it yesterday. Woops. I was building out an email sending feature, and the basic idea was to assign a role to a user th... [Read Full]
markdown guide
 
 

I don't have all the context of your application but they way I understood, if the role is not updated for some reason, the user will get notified that they have a super power when they not. You should move the check after the role is updated.

Also it's worth the mention that attr_acccessor (Ruby method apidock.com/ruby/Module/attr_accessor) acts as an alias for attr_reader and attr_writer methods, both options will work for this case.

Examples:

attr_writer :superpower_email

# generates
def superpower_email=(value);
  @superpower_email = value
end

# -
attr_reader :superpower_email

# generates
def superpower_email
  @superpower_email
end

# -
attr_accessor :superpower_email

# generates
def superpower_email=(value)
  @superpower_email = value
end

def superpower_email
  @superpower_email
end

Hope this makes it clear, since the line about why you use attr_accessor can be misleading.

Good writing, thanks for sharing.

 

Gotcha, thanks for that. I updated my article to clarify my point.

And yeah, good point about the email sending even if the role is not properly updated.

Thanks for reading!

 

There is a typo mistake.

  attr_acccessor superpower_email

should be

  attr_accessor :superpower_email
 
code of conduct - report abuse