方法
实例公共方法
except(*skips) 链接
从查询中移除 skips 中指定的条件。
Post.order('id asc').except(:order) # removes the order condition Post.where('id > 10').order('id asc').except(:where) # removes the where condition but keeps the order
来源: 显示 | 在 GitHub 上
# File activerecord/lib/active_record/relation/spawn_methods.rb, line 59 def except(*skips) relation_with values.except(*skips) end
merge(other, *rest) 链接
如果 other 是一个 ActiveRecord::Relation,则合并来自 other 的条件。如果 other 是一个数组,则返回一个表示结果记录与 other 的交集的数组。
Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) ) # Performs a single join query with both where conditions. recent_posts = Post.order('created_at DESC').first(5) Post.where(published: true).merge(recent_posts) # Returns the intersection of all published posts with the 5 most recently created posts. # (This is just an example. You'd probably want to do this with a single query!)
Proc 将通过 merge 进行评估
Post.where(published: true).merge(-> { joins(:comments) }) # => Post.where(published: true).joins(:comments)
这主要用于在多个关联之间共享通用条件。
对于两个关系中都存在的条件,来自 other 的条件将优先。要查找两个关系的交集,请使用 QueryMethods#and。
来源: 显示 | 在 GitHub 上
# File activerecord/lib/active_record/relation/spawn_methods.rb, line 33 def merge(other, *rest) if other.is_a?(Array) records & other elsif other spawn.merge!(other, *rest) else raise ArgumentError, "invalid argument: #{other.inspect}." end end
only(*onlies) 链接
仅保留查询中 onlies 指定的条件,移除所有其他条件。
Post.order('id asc').only(:where) # keeps only the where condition, removes the order Post.order('id asc').only(:where, :order) # keeps only the where and order conditions
来源: 显示 | 在 GitHub 上
# File activerecord/lib/active_record/relation/spawn_methods.rb, line 67 def only(*onlies) relation_with values.slice(*onlies) end