Reputation: 14504
I have this action in my controller:
def ad
@koder = @side.reklamers.pluck(:id) - [session[:log]]
@reklame = Reklamer.find(@koder.sample)
session[:log] = @reklame.id
render :text => "<span class='bannerid' data-id='#{@reklame.id}'></span><p style='margin-bottom: 7px;margin-top: 7px;font-size: 9px;text-align: center !important;'>Ad</p>#{@reklame.kode}"
end
It renders an HTML ad. This code is really fast. The problem is when I do try to example count view the response becomes VERY slow. 3s. Compared to 200ms!
@koder = @side.reklamers.pluck(:id) - [session[:log]]
@reklame = Reklamer.find(@koder.sample)
session[:log] = @reklame.id
@reklame.views += 1
@reklame.save
render :text => "<span class='bannerid' data-id='#{@reklame.id}'></span><p style='margin-bottom: 7px;margin-top: 7px;font-size: 9px;text-align: center !important;'>Ad</p>#{@reklame.kode}"
I have tried to add a resque background job with the same result..
What should I do?
Upvotes: 0
Views: 593
Reputation: 2519
First, try:
@reklame.update_attribute :views, @reklame.views + 1
See if that helps. If so, then you have some costly data validations going on that are slowing you down, but at least you know the source of the problem.
If that doesn't work, try wrapping that statement in
Thread.new { //code }
If it's still slow doing the save, then it's probably how your database is set up or something along those lines.
Upvotes: 0
Reputation: 7715
Since views
is really a counter maybe you should take a look at:
http://apidock.com/rails/v3.2.13/ActiveRecord/CounterCache/increment_counter
In your case it should look like this
Reklamer.increment_counter(:views, @reklame.id)
It should update only views column, don't run validations, callbacks etc. which will make it faster. But on the other hand 3s on simple save indicates that there is something else going wrong also.
Upvotes: 2