Reputation: 45
In conversations with a teammate, we were asking ourselves when Rails turns values given to a boolean field into true
/false
.
In Rails, saving a value from certain certain "FALSE_VALUES" (like false, 'FALSE', 0, '0'
... https://github.com/rails/rails/blob/6-1-stable/activemodel/lib/active_model/type/boolean.rb) will be saved as false
in the ActiveRecord record (if the column type is boolean, of course). All other values (I think) will be saves as true
Knowing this is great, but when are those values actually "turned" to either true
or false
?
Is this comparable to any callback (e.g. before_validation
)? In our case especially, can we make sure it runs before validations are run?
If anyone even finds where this is stated within the rails code, it would be awesome pointing to that :)
Upvotes: 2
Views: 1356
Reputation: 102046
When you set a value in your model the setter will typecast the value:
class Thing
include ActiveModel::Model
include ActiveModel::Attributes
attribute :awesome, :boolean
end
t = Thing.new
t.awesome = "1"
t.awesome # true
If you want to tap into the process the most straight forward way is by redefining the setter.
class Thing
include ActiveModel::Model
include ActiveModel::Attributes
attribute :awesome, :boolean
def awesome=(value)
# do something
super
end
end
When you initialize, create or update a model from a Hash of attributes ActiveModel::AttributeAssignment handles setting the attributes from a hash by looping through the keys and values and calling the appropriate setter.
ActiveModel::Attributes
is a previously private API that was exposed in Rails 5 and it forms the cornerstone of ActiveRecord::Attributes
which is a more specialized implementation where the model is backed by a database table. In ActiveRecord::Attributes
the typecasting is also done in the setter but it also includes stuff like dirty tracking and keeps track of attributes even before they are typecast. ActiveRecord::Attributes
not only handles typecasting user input but it also handles typecasting values to and from the database.
ActiveRecord also includes a whole multitude of methods for assigning and updating methods that vary in if they fire callbacks or validations.
"Is this comparable to any callback (e.g. before_validation)? In our case especially, can we make sure it runs before validations are run?
This really depends on which method we are talking about. But in most cases the actual assignment happens before any callbacks are run.
See:
Upvotes: 3