0
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?

keruilin
  • 16,782
  • 34
  • 108
  • 175
  • 2
    Could you please format the code? Just click the button to edit your question, highlight the code, and click on "101/010". – Wayne Conrad Jan 15 '10 at 04:42

2 Answers2

5

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
mahatmanich
  • 10,791
  • 5
  • 63
  • 82
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Instead of using the `!!` trick, it would be clearer to use: `exists? ["? not in (...) and ? not in (...)", user_id, todo_id]` – Alex Reisner Jan 15 '10 at 22:05
0

Thx. I discovered the issues! I ended up writing this:

def incomplete?(user_id, todo_id) return UserTodo.find_by_sql("select case when (#{user_id} not in (select user_id from user_todos)) and (#{todo_id} not in (select todo_id from user_todos)) then true else false end as incomplete from user_todos") end

But I like your approach better.

keruilin
  • 16,782
  • 34
  • 108
  • 175