DEV Community

TIL You Can Add Virtual Attributes to Rails Models

Andy Zhao (he/him) 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...
Collapse
 
jess profile image
Jess Lee

ooooh i got a shout out 😍

Collapse
 
kinduff profile image
Alejandro AR • Edited

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.

Collapse
 
andy profile image
Andy Zhao (he/him)

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!

Collapse
 
roshan92 profile image
Roshan

There is a typo mistake.

  attr_acccessor superpower_email

should be

  attr_accessor :superpower_email
Collapse
 
andy profile image
Andy Zhao (he/him)

Fixed, thanks!

Collapse
 
almokhtar profile image
almokhtar bekkour

btw where did you asked for help ? it a rails slack ?