Alan Alves de Oliveira
Alan Alves de Oliveira

Reputation: 713

How to make Rails use the getter method of a property when saving the activerecord on DB?

I have an activerecord like this

# == Schema Information
#
# Table name: cars
#
#  id                  :bigint(8)        not null, primary key
#  year                :integer
#  type                :string(255)
#
class Car < ApplicationRecord
  def type
    return self[:type] if self[:type].present?
    year > 2010 ? 'new' : 'old'
  end
end

When I run Car.create(year: 2019) it is saving the type as nil instead use the getter value.

Is it possible to use the getter value on saving in database?

Upvotes: 0

Views: 220

Answers (2)

Gagan Gupta
Gagan Gupta

Reputation: 1227

Your after_create is not working because you're not saving it afterwards.

you can use :before_create

def set_type
  if year
    self.type = year > 2010 ? 'new' : 'old'
  end
end

Upvotes: 0

fphilipe
fphilipe

Reputation: 10054

You could set the type when setting the year. For that, override the default setter for year:

def year=(value)
  super
  self.type = value > 2010 ? 'new' : 'old'
end

Car.create(year: 2019) will call each property's setter, in this case #year=, which will set the type.

Upvotes: 1

Related Questions