【问题标题】:How to return boolean result in named_scope?如何在 named_scope 中返回布尔结果?
【发布时间】:2010-01-15 03:29:01
【问题描述】:
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)" ]
  } 
}

我得到一个 nil 结果。我希望它返回 true。我该怎么办!?

另外,有没有更好的写法?

【问题讨论】:

  • 能否请您格式化代码?只需点击按钮编辑您的问题,突出显示代码,然后点击“101/010”。

标签: ruby-on-rails ruby boolean named-scope


【解决方案1】:

您的代码存在一个大问题:命名范围不打算返回布尔值或单个值,而是打算返回要链接的过滤器。

改用类方法。另外,使用插值,不要将值直接写入 SQL 代码。

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

【讨论】:

  • 与其使用!!技巧,不如使用:exists? ["? not in (...) and ? not in (...)", user_id, todo_id]
【解决方案2】:

谢谢。我发现了问题!我最终写了这个:

def 不完整?(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 complete from user_todos") 结束

但我更喜欢你的方法。

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2022-01-06
    • 2019-03-12
    • 1970-01-01
    • 2011-06-19
    相关资源
    最近更新 更多