views:

336

answers:

3

for example, I have a table 'post' and column 'views'. When people view the post each time, the 'views' will be added 1. Now my step is

@post = Post.find_by_id(params[:id])
@post.views += 1
@post.save

Is there any better way to add 'views'?

+2  A: 

It depends on your needs. If you just need to count views of the post, then I would just advise to move that line into a method in your model. If you need something more complex, you may have to introduce a model for a view, including the user that viewed the post, a timestamp of the view, etc.

neutrino
+4  A: 

Use increment method:

@post.increment!(:views)

You can make it shorter

Post.find(params[:id]).try(:increment!,:views)

Notice the use of try method cause a post record with that id might not exist.

khelll
If it doesn't exist, the find will fail with an exception anyway
Anton
That's the idea of it, to avoid the exception.
khelll
+1  A: 

I second neutrino -- you should move that logic into a method inside the model. And probable use khelll's suggestion of using increment. Something like:

class Post < ActiveRecord::Base
  ...

  def increment_views
    self.increment!(:views)
  end
  ...
end

This way if you ever need to do more stuff then you need to change the model method only.

rohit.arondekar
Terrible mistake to make, thanks for fixing it khelll.
rohit.arondekar