0
votes

I'm trying to setup an attribute that isn't saved to the database but I can't work out how to change it and read the new value.

class User < ApplicationRecord
  attribute :online, :boolean, default: false
end

in Rails Console:

User.first.online = true
=> true
User.first.online
=> false

I'm running Ruby-on-rails 5.2.4.1 and ruby 2.4.1 https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute

1
Your question is unclear to me. I decided to use the attribute method and you know that these kinds of attributes are not saved into the database. But at the same time, you expect that the attribute should be persistent? Why do not you just save it into the database? How do you think the attribute should be persistent when it is not stored in the DB?spickermann

1 Answers

2
votes

The line:

User.first

Creates an instance for the first user each time you call it.

User.first.equal?(User.first) #=> false
#          ^^^^^^
# Equality — At the Object level, returns true only if obj
# and other are the same object.

You're setting the online attribute of a different instance than the one you're reading from (although they represent the same record). Store the user in a variable. That way you're working with the same instance for both the set and get call.

user = User.first
user.online = true
user.online #=> true