Increasing counter in database - ruby-on-rails

I have field called ads_counter in my database, and I need to increase its value each time when this ad is rendered.
I tried to write a custom method and use it in the controller responsible for this data, but that didn't work. Are there any built-in methods to increase the value of a field in the database?

Yes, there is the increment method that you can call in your ActiveRecord.
For reference: increment
Edit:
To make it save directly use the increment!
You may use it this way:
instance.increment!(:ads_counter)
It automatically increments by 1
instance.increment!(:ads_counter, <number>)
It increments by number provided

You have the method increment! that increments an attribute and saves the record
your_object.increment!(:ads_counter)
Put this code in the show method of your controller.

You can try increment! method
object.increment!(:method_name)

Related

Callback in Rails

I want to call a function after a particular form is submitted in my mobile app. I am calling it as :
after_save :insert_into_my_table, on: :save_playing_request
save_playing_request is the function which saves the new form. I want to call insert_into_my_table after this. Is it the correct way?
It is not correct way, I think you should use conditional callback or you can also try to customize this as per your requirement.
Like below code.
save_playing_request is just save the data then it should return true/false.
then we can use 'if' with callback.
after_save :insert_into_my_table, if: :save_playing_request?
Now you need to change your method name.
save_playing_request => save_playing_request?

Increment field value in a CKRecord variable without fetching?

I am curious is it somehow possible to increment a field value in a CKRecord variable without fetching? So on client I am not curious about the recent value, I just want to increase whatever be the value is. The reason, operation should be as quick and easy as possible, instead of two message 'stream', I want initiate only one.
Unfortunately you can not. You have to read, change and then write the record. Make sure that you use the CKModifyRecordsOperation and leave the savePolicy to CKRecordSaveIfServerRecordUnchanged If you get an error then you could try read and write the record again.

Get group by data in rails using psql in rails [duplicate]

I've got a query that does some math and returns a calculated custom select field with the result set. I cannot figure out how to access that in the activerecord object that is returned. I've added an attr_accessor for it also.
attr_accessor :percentage_used
select('gateways.*, (num_transactions_today/ SUM(num_transactions_today)) AS percentage_used ').joins(:gateway_groups).where('map_gateway_groups.gateway_group_id = ?', gateway_group_id)
in the result set, I would expect to have access to :percentage_used, but it is not in there. Any ideas on what i'm doing wrong? i've never needed to do this before.
Thanks
You can access it as
object["percentage_used"]
You neither need nor want attr_accessor for that. attr_accessor creates an instance variable, an accessor method for getting the value of that instance variable, and a mutator method for changing its value. When you say this:
select('gateways.*, (num_transactions_today/ SUM(num_transactions_today)) AS percentage_used ...
ActiveRecord will automatically add a percentage_used method to the returned objects. But the percentage_used method for accessing that value will be added by method_missing. Since you've said attr_accessor :percentage_used, method_missing will never be called and you can't get at the percentage_used value from the query in the usual way.
If you drop the attr_accessor :percentage_used, then you'll be able to call percentage_used on objects returned by that select and you'll find the values you're looking for. However, AR won't be able to convert the value to a native Ruby number though so you'll have to to_f the returned string yourself.

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.

Ruby On Rails self saving in model

I have a function in my model that changes is as follows:
def compare
self.dirty = 1 if self.dirty == 0
compare_recursive(0, MergeDigestTree.all)
self.dirty = 0;
end
Do I have to call self.save or is it fine like this
Your question is open to two interpretations:
Do you have to call self.save so the record is saved at this point? yes, because an attribute assignation does not commit the change to the database.
Are you forced to call self.save and thus save the record? no. It's ok for a method to change the instance and do not save it. I usually prefer this one, as you give more freedom to the caller.
Whatever the case, document the method accordingly.
You will have to save it yourself, yes. Though I don't see what that method is really doing. :)
No, you should have to call save once changes are made, at some point after this function, if not within this function...
so if you're using this function manually in your app...
resource.compare()
resource.save
Would be fine if you don't want to put the self.save in the compare function.

Resources