Check if model instance falls within named_scope in rails

后端 未结 2 1004
眼角桃花
眼角桃花 2021-02-14 18:23

Assume I have a named scope:

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

This works great

2条回答
  •  借酒劲吻你
    2021-02-14 18:42

    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.

提交回复
热议问题