检查模型实例中轨named_scope之内 [英] Check if model instance falls within named_scope in rails

查看:239
本文介绍了检查模型实例中轨named_scope之内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为范围:

Assume I have a named scope:

class Foo < ActiveRecord::Base
    named_scope :bar, :conditions => 'some_field = 1'
end

这伟大工程的查询和我有一大堆有用的定义的named_scopes。我想是能够做到这一点:

This works great for queries and I have a bunch of useful named_scopes defined. What I would like is to be able to do this:

f = Foo.find(:first)
f.some_field = 1
f.is_bar? #=> true

在'的.bar?如果模型实例属于一个名为范围内的方法只会返回true或false。反正有做到这一点,而无需编写的is_bar?即使我已经写检查,如果事情的好办法法is_bar?如果我没有记错,干好所以任何帮助将不胜AP preciated /

The '.bar?' method will simply return true or false if the model instance falls within the named scope. Is there anyway to do this without writing an 'is_bar?' method even though I've already written a good way to check if something 'is_bar?' If I remember correctly, DRY is good so any help would be greatly appreciated/

推荐答案

您可以致电的存在?上一个名为范围的方法,将查询数据库,看是否定记录存在该等条件。

You can call the exists? method on a named scope which will query the database to see if the given record exists with those conditions.

Foo.bar.exists?(f)

不过,如果你已经改变了属性˚F,它不保存到数据库中这是行不通的。这是因为,命名范围条件的SQL所以检查必须发生在那里。尝试转换为Ruby的如果条件是凌乱的,尤其是在比较复杂的情况。

However this will not work if you have changed the attributes on f and not saved it to the database. This is because the named scope conditions are SQL so the check must happen there. Attempting to convert to Ruby if conditions is messy, especially in more complex scenarios.

这篇关于检查模型实例中轨named_scope之内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆