views:

275

answers:

1

Assume I have a named scope:

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

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

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/

+5  A: 

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)

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.

ryanb
thanks. Ok so pretend I called .save after changing the value. Foo.bar.exists?(Foo.find(:first)) will return true or false depending if it falls within the bar scope? Awesome.
Correct. You shouldn't have to call Find again either. "f.save; Foo.bar.exists?(f)" should work.
ryanb