【问题标题】:Adding conditions to all finds in a model in Ruby on Rails 3在 Ruby on Rails 3 中为模型中的所有查找添加条件
【发布时间】:2013-09-18 14:05:43
【问题描述】:

尝试在 google 上搜索所有内容,但在 Ruby on rails 中找不到类似于 CakePHP 的 beforeFind() 回调的任何内容。

所以我目前有一个新闻模型。

    class News < NewsRecord
    end

新闻模型的 find 方法已经在站点周围许多地方的控制器中使用。我现在向新闻模型添加了一个 publish_web(boolean) 列。

我想要在此新闻模型中添加一个条件,该条件将添加到此模型上发生的所有查找条件中。所以是这样的:

    class News < NewsRecord
        :conditions => {:published_web => true}
    end

【问题讨论】:

    标签: database-design activerecord model rails-activerecord


    【解决方案1】:

    您可能想要使用范围,一种方法是

    class News < NewsRecord
      scope :published, where(published_web: true)
    end
    

    这将允许您执行News.published 并将返回符合范围内条件的所有记录。

    另一种方法是设置一个default_scope,它将用default_scope 中的条件“替换”News 表中的所有获取(请记住,这可能是“危险的”)。

    class News < NewsRecord
      default_scope where(published_web: true)
    end
    

    【讨论】:

    • 是的,谢谢! default_scope where(:publish_web => true) #替代语法
    • 是的,这也是一个有效的语法,编辑了我的答案以使其更清晰。
    • 如果它有帮助并且您可以投票/接受答案,我将非常感激 =)
    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多