user2954587
user2954587

Reputation: 4861

Write attribute to active record object

I'm trying to write an attribute to an active record object before returning it to the client.

user = User.find(18).profile

I'd then like to set user[:random_attribute] = 'random_attribute'

But I get the following error message

ActiveModel::MissingAttributeError (can't write unknown attribute random_attribute'):

what's the best way to add random data to a record before returning it to the client?

Upvotes: 1

Views: 1231

Answers (1)

emk
emk

Reputation: 185

Seems like what you need is a virtual attribute (there is quite a lot of information about ActiveRecord virtual attributes).

class User < ActiveRecord::Base
  def random_attribute
    # ...
  end
end

If you want to assign the random_attribute value somewhere else in your code, you can do so by defining the corresponding getter and setter methods just like in any other Ruby class by using attr_accessor.

class User < ActiveRecord::Base
  attr_accessor :random_attribute
end

a = User.new
a.random_attribute = 42
a.random_attribute # => 42

Another way to define the getter and setter methods (in case you might need something more sophisticated):

class User < ActiveRecord::Base
  def random_attribute(a)
    @random_attribute
  end

  def random_attribute=(a)
    @random_attribute = a
  end
end

Keep in mind though that during serialization, that attribute won't be included by default, so if you need this attribute in json, you might have to pass the corresponding arguments to the to_json method.

puts a.to_json(methods: [:random_attribute])
# => { ... "random_attribute":42}

Upvotes: 1

Related Questions