【发布时间】:2011-02-20 04:40:50
【问题描述】:
我有一个模型Post,它有一个名为is_viewed 的字段,在创建Post 时它是假的。
当帖子显示给用户时,将 is_viewed 设置为 true 的最佳方法是什么?
目前,我必须这样做:
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
为了只加载一次帖子,我可以这样做:
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
但这是正确的做法吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3