Search code examples
ruby-on-railsrubybooleannamed-scope

How to return boolean result in named_scope?


named_scope :incomplete?, lambda { |user_id, todo_id| 
  { :select => 1, :conditions =>
    [ "#{user_id} not in (select user_todos.user_id from user_todos) and
       #{todo_id} not in (select user_todos.todo_id from user_todos)" ]
  } 
}

I'm getting a nil result. I want it to return true. What I gotta do!?

Also, is there a better way to write this?


Solution

  • There's a huge issue with your code: named scopes are not intended to return booleans or single values, are intended to returns filters to be chained.

    Use a class method instead. Also, use interpolation, don't write values directly into the SQL code.

    class YourModel
      def self.incomplete?(user_id, todo_id)
        exists?(["? not in (select user_todos.user_id from user_todos) and ? not in (select user_todos.todo_id from user_todos)", user_id, todo_id])
      end
    end