How to mark a post as viewed?
I have a model, Post
, which has a field called is_viewed
, which is false when a Post
is created.
What is the best way to set is_viewed
to true when a post is shown to the user?
Currently, I am having to do this:
class PostsController..
def show
#find the post
@post = current_user.posts.find(params[:id])
if !@post.is_viewed?
#mark as viewed
开发者_运维问答 @post.update_attribute(:is_viewed, true)
#find the post (again)
@post = current_user.posts.find(params[:id])
end
end
end
In order to load the post only once, I could do this:
if !@post.viewed?
if @post.update_attribute(:is_viewed, true)
#simply update the viewed to true, "in memory" so that
#the view's erb can use the correct value of the "is_viewed" variable
@post.viewed = true
end
end
But is that the right thing to do?
Your ruby isn't very rubyish. Typically one doesn't use 'is_' as a prefix as ruby allows method names to end with a question mark. Assuming your field is a boolean you can use @post.viewed?
as a shorthand.
Anyway to answer your question, because of ActiveRecord::Dirty there's really no need to check the current state. If you call @post.save
on a post for which @post.changed?
is false, no update query will be run. So:
@post = current_user.posts.find(params[:id])
@post.viewed = true
@post.save
You don't say why your code reloads the post so I'm going to assume that's bogus. Ruby has an unless
keyword so you can replace constructions like if !expr
with unless expr
.
Also, ruby code looks best indented with 2 spaces :-)
精彩评论