【问题标题】:How to mark a post as viewed?如何将帖子标记为已查看?
【发布时间】: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


    【解决方案1】:

    你的红宝石不是很红。通常不使用 'is_' 作为前缀,因为 ruby​​ 允许方法名称以问号结尾。假设您的字段是布尔值,您可以使用 @post.viewed? 作为速记。

    无论如何回答你的问题,因为 ActiveRecord::Dirty 真的没有必要检查当前状态。如果您在@post.changed? 为假的帖子上调用@post.save,则不会运行更新查询。所以:

    @post = current_user.posts.find(params[:id])
    @post.viewed = true
    @post.save
    

    你没有说为什么你的代码会重新加载帖子,所以我会假设那是假的。 Ruby 有一个 unless 关键字,因此您可以将 if !expr 等结构替换为 unless expr

    此外,ruby 代码看起来最好缩进 2 个空格 :-)

    【讨论】:

    • 感谢您的见解。当显示帖子时,我将viewed设置为true(即代码在帖子控制器的显示操作中执行)。如果我使用您的代码,我会将viewed 设置为true,无论它是否已经设置,因此每次显示帖子时都会写入表格。另外,当只更新其中一个字段时,为什么要写出所有字段?附言。更新了我的代码以显示一些上下文。此外,还需要第二次重新加载,以便在渲染视图时,视图的 .erb 也可以知道所查看字段的实际状态。
    • 也许您可以尝试阅读我的答案。就像它说的那样,因为 AR::Dirty 除非有必要,否则不会写入。而且由于您想将帖子标记为第一次查看,因此后续查看将无效。从这个意义上说,动作是幂等的。
    • 谢谢你,面条。我现在正在使用update_attribute 进行更新,并且以类似的方式工作。
    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多