I have a Picture model that contains a variable for a view count (integer). The view count is incremented by +1 every time someone views the Picture object.
In getting this done, what is the difference between
@picture.view_count += 1 @picture.save
and
@picture.increment(:view_count, 1)
also if i use increment, is .save necessary?
These two are exactly the same. It's just two different ways of writing the same thing. i++ is just a shortcut for i += 1 , which itself is a shortcut for i = i + 1 . These all do the same thing, and it's just a question of how explicit you want to be.
++i is sometimes faster than, and is never slower than, i++. For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.
As i++ does automatic typecasting and uses a compiler instruction which internally uses iadd instruction, i=i+1 is faster than i++.
i+=i means the i now adds its current value to its self so let's say i equals 10 using this += expression the value of i will now equal 20 because you just added 10 to its self. i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. 3rd January 2020, 3:15 AM.
The source of increment
is below, which initializes attribute to zero if nil and adds the value passed as by (default is 1), it does not do save, so .save
is still necessary.
def increment(attribute, by = 1) self[attribute] ||= 0 self[attribute] += by self end
I often use counter_cache
and increment_counter
in that case.
like this:
Picture.increment_counter(:view_count, @picture.id)
This way is more simple and faster than self-made method.
Incidentally, ActiveRecord::CounterCache has also decrement_counter
.
http://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With