Update serialized attribute without callbacks in Rails - ruby-on-rails

I am trying to update a serialized attribute with some data in an after_save callback on the same object.
I don't want any callbacks to be triggered, for various reasons (side-effects, infinite loop). The typical way to achieve this would be to use update_column, but unfortunately that doesn't work with serialized attributes.
I am aware that I could put conditionals on my callbacks to avoid them getting called again, but it feels that there should be a form of update_attribute which doesn't trigger callbacks, but still works with serialized attributes.
Any suggestions?

This is what I do
serialize :properties, Hash
def update_property(name, value)
self.properties[name] = value
update_column(:properties, properties)
end

Sharing an example below how you can update serialize attribute without callbacks.
Suppose you have a train object, and there is a serialize attribute in that table called: "running_weekdays", that store on which day that particular train runs.
train = Train.last
train.running_weekdays
=> {"Mon"=>"true", "Tues"=>"true", "Wedn"=>"true", "Thur"=>"true", "Frid"=>"true", "Sat"=>"true", "Sun"=>"true"}
Now suppose you want to set the value for all weekdays as false except 'Monday'
changed_weekdays = {"Mon"=>"true", "Tues"=>"false", "Wedn"=>"false", "Thur"=>"false", "Frid"=>"false", "Sat"=>"false", "Sun"=>"false"}
Now you can update this by using update_column as below:
train.update_column(:running_weekdays, train.class.serialized_attributes['running_weekdays'].dump(changed_weekdays))
Hope this will help.

You need to code the hash before updating the column:
update_column(:properties, self.class.serialized_attributes['properties'].dump(properties))

Related

How to mark as outdated an ActiveRecord object attribute?

I have a database trigger that modifies a field on INSERT. Then when I run object.my_attribute it returns nil instead of lets say 42.
If I do object.reload.my_attribute, this is fine. But I don't want to reload the whole object or part of it unless it is necessary. And I believe code shouldn't be concerned when and how an object was created. It should just be correct.
Is it possible to mark that particular attribute as outdated and any attempt to get its value to result in a query that fetches it from database?
For example:
after_save :forget_my_attribute
def forget_my_attribute
forget_field :my_attribute
end
I think it's better to make some service object where field is modified and call it when create the record. CreateModel.call(args) instead of Model.create(args). It will be more clear than database trigger I think
But you can do something like this
after_create_commit :fetch_my_attribute
def fetch_my_attribute
self[:my_attribute] = self.class.find_by(id: id)[:my_attribute]
end
Or more flexible fetch attribute you need dynamically
def fetch_attribute(atr)
self[atr] = self.class.find_by(id: id)[atr]
end
object.fetch_attribute(:my_attribute)

Rails - Returning all records for who a method returns true

I have a method:
class Role
def currently_active
klass = roleable_type.constantize
actor = Person.find(role_actor_id)
parent = klass.find(roleable_id)
return true if parent.current_membership?
actor.current_membership?
end
end
I would like to return all instances of Role for who this method is true, however can't iterate through them with all.each as this takes around 20 seconds. I'm trying to use where statements, however they rely on an attribute of the model rather than a method:
Role.where(currently_active: true)
This obviously throws an error as there is no attribute called currently_active. How can I perform this query the most efficient way possible, and if possible using Active Records rather than arrays?
Thanks in advance
It seems impossible, in your case you have to do iterations. I think the best solution is to add a Boolean column in your table, so you can filter by query and this will be much faster.
After seeing your method after edit, it seems that it's not slow because of the loop, it is slow because Person.find and klass.find , you are doing alot of queries and database read here. (You better use associations and do some kind of eager loading, it will be much faster)
Another work-around is you can use ActiveModelSerializers , in the serializer you can get the attributes on the object based on condition. and after that you can work your logic to neglect the objects that have some kind of flag or attribute.
See here the documentation of active model serializer
Conditional attributes in Active Model Serializers
Wherever possible you better delegate your methods to SQL through activerecord when you're seeking better efficiency and speed and avoid iterating through objects in ruby to apply the method. I understand this is an old question but still many might get the wrong idea.
There is not enough information on current_membership? methods on associations but here's an example based on some guess-work from me:
roleables = roleable_type.pluralize
roleable_type_sym = roleable_type.to_sym
Role.joins(roleables_sym).where(" ? BETWEEN #{roleables}.membership_start_date AND #{roleables}.membership_end_date", DateTime.current).or(Role.joins(:person).where(" ? BETWEEN persons.membership_start_date AND persons.membership_end_date", DateTime.current))
so you might have to re-implement the method you have written in the model in SQL to improve efficiency and speed.
Try the select method: https://www.rubyguides.com/2019/04/ruby-select-method/
Role.all.select { |r| r.currently_active? }
The above can be shortened to Role.select(&:currently_active?)

Only update records that haven't been updated

When creating a record i know you can use the method
.first_or_create!
to create records that don't already exist in the model. I need to do the same for when updating a model. I have an app that runs a rake task to apply a score to a column in my model.
prediction.update_attributes!(score: score)
I only want to update the scores that have not been updated yet.
is this possible?
Thanks
I think you might be looking for the try method which will attempt to call a method on an object that is potentially nil.
Example:
>> prediction.try(:update_attributes!, :score => some_new_score)
If prediction is nil it will just return nil, not throw a NoMethodError. If prediction is an object representing an existing record, then it will call the method on the object and update its score attribute.
http://api.rubyonrails.org/classes/Object.html#method-i-try
I agree with juanpastas that Rails will only save to the db if something has actually changed. IF you want to be more explicit in your code, Why not use the '.changed?' flag to save only dirty records? Look here for more details.

Send parameter to before_save

I am trying to build an app in the "rails way", so this time instead of retrospectively processing records in the database, I am trying to do them using a before_save method, namely this one:
def make_percentage_from(score)
percent = (score.fdiv(20) * 100)
return percent
end
Every item that comes into the database has a score out of 20, before it gets saved to the database I would like to store this as a percentage, however the issue I am having is that I am unable to send any attribute data via a before_save.
Ideally I'd have
before_save :make_percentage_from(score-to-be-calculated)
How can I do this? Google isn't turning up so much for me and I'm determined not to have to process this data once its stored (providing of course there is another way!)
Thanks and regards
Geoff
The short answer: callbacks never have parameters. It is assumed that callbacks take action on the object or record itself. So anything that you would need as a parameter you would need to store either as an attribute (which is saved to the database) or as an instance variable.
If score and percentage are attributes of Widget:
class Widget < ActiveRecord::Base
before_validates :calculate_score_percentage
validates :percentage, :presence => true
private
def calculate_score_percentage
self.percentage = score.fdiv(20) * 100
end
end
This works because all of your attributes/columns have getter and setter methods automatically defined by ActiveRecord. The reference to score in the calculate_score_percentage method is actually calling the self.score method, which will return the score object/value. We have to use self.percentage explicitly because it would be ambiguous to use percent alone — it could be either defining a local percentage variable, or calling self.percentage=. The default would be the former, which is not what we want in this case.
I'm using before_validates to show that you can use validation still here, which is good for some sanity checking. If you didn't want to do any validation, you could swap it out for before_save without any code changes.

How to update all when you need callbacks fired?

Let's say I've got 15 user ids in an array called user_ids.
If I want to, say, change all of their names to "Bob" I could do:
users = User.find(user_ids)
users.update_all( :name => 'Bob' )
This doesn't trigger callbacks, though. If I need to trigger callbacks on these records saving, to my knowledge the only way is to use:
users = User.find(user_ids)
users.each do |u|
u.name = 'Bob'
u.save
end
This potentially means a very long running task in a controller action, however.
So, my question is, is there any other better / higher performance / railsier way to trigger a batch update to a set of records that does trigger the callbacks on the records?
Instead of using each/find_each, try using update method instead:
models.update(column: value)
Which is just a wrapper for the following:
models.each{|x| x.update(column: value)}
Here's another way of triggering callbacks. Instead of using
models.update_all(params)
you can use
models.find_each { |m| m.update_attributes(params) }
I wouldn't recommend this approach if you're dealing with very large amounts of data, though.
Hope it helps!
No, to run callbacks you have to instantiate an object which is expensive operation. I think the only way to solve your problem is to refactor actions that you're doing in callback into separate method that could use data retrieved by select_all method without object instantiation.

Resources