代码之家  ›  专栏  ›  技术社区  ›  Yuval Karmi

在RubyonRails中,在哪里放置一段代码?

  •  1
  • Yuval Karmi  · 技术社区  · 14 年前

    我有一个帖子管理员,有很多评论。 post模型有一个名为has_comments的字段,它是一个布尔值(因此我可以快速地从数据库中选择只有注释的文章)。 要为文章创建新评论,我使用 create 我的评论控制者的行动。

    创建评论后,我需要更新我的帖子的has_comment s字段并将其设置为 true .

    我可以从 创造 我的评论控制者的行动,但这似乎不正确-我觉得我真的应该使用帖子的 update 行动,但我不确定打电话是不是正确(通过 send ?)来自注释控制器的创建操作。

    更新日志的代码应该在哪里? 谢谢您!

    3 回复  |  直到 14 年前
        1
  •  2
  •   Dave Sims    14 年前

    当接口是可编程的时,为什么要用另一列来混乱数据库?make has_comments a method on post:

    def has_comments
      comments.size > 0
    end
    

    然后按照建议实现一个计数器缓存,以减少查询负载。

    编辑:或者,在实现计数器缓存之后,您可以使用post上的命名_scope来检索具有注释的所有文章,如果这是主要目标:

    class Comment
      belongs_to :post, :counter_cache => true
    end
    
    class Post
      named_scope :with_comments, {:conditions=>"comments_count > 0"}
    end 
    

    编辑:您还可以明智地使用:包括:来避免著名的N+1查询问题:

    posts = Post.find(:all, :include => :comments)
    
        2
  •  1
  •   Slobodan Kovacevic    14 年前

    您可以在模型中保存回调之前使用。

    更好的方法是使用内置的:counter-cache选项,该选项自动缓存每个帖子的注释数。(见 http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001835 在“属于”的选项下)

        3
  •  1
  •   Salil    14 年前

    在注释模型中保存后使用

    def after_save
      #this will set "has_comment" of the Specified Post to true if it's not true already
      self.post.update_attribute('has_comment', true) unless self.post.has_comment
    end