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'?
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'?
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.
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.
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.