tee*_*tee 12 activerecord scope ruby-on-rails-3
我有一个Rails 3范围,它排除了一系列ID.
编写范围的最佳方法是什么,以便在数组为空且仍可链接时它不执行任何操作?我目前有这个,它的工作原理,但似乎有点兴奋:
scope :excluding_ids,
lambda {|ids| ids.empty? ? relation : where('id not in (?)', ids) }
Run Code Online (Sandbox Code Playgroud)
如果我没有"ids.empty ??关系:"位,当id为空时,生成的SQL就是
... ID not in (NULL) ...
Run Code Online (Sandbox Code Playgroud)
这将永远不会返回.所以类似于:
Model.excluding_ids([]).where('id > 0')
Run Code Online (Sandbox Code Playgroud)
没有结果.
Dou*_*rer 19
如果ids数组为空,则不返回任何内容.
scope :excluding_ids, lambda { |ids|
where(['id NOT IN (?)', ids]) if ids.any?
}
Run Code Online (Sandbox Code Playgroud)
如果没有,查询将在没有任何额外约束的情况下运行ids.
在Rails 4中,您可以使用:
scope :excluding_ids, ->(ids) { where.not(id: ids) }
Run Code Online (Sandbox Code Playgroud)