跳至内容 跳至搜索
方法
E
M
O

实例公共方法

except(*skips)

从查询中移除skips中指定的一个或多个条件。

Post.order('id asc').except(:order)                  # discards the order condition
Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
# File activerecord/lib/active_record/relation/spawn_methods.rb, line 59
def except(*skips)
  relation_with values.except(*skips)
end

merge(other, *rest)

如果otherActiveRecord::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!)

Procs 将由 merge 评估。

Post.where(published: true).merge(-> { joins(:comments) })
# => Post.where(published: true).joins(:comments)

这主要用于在多个关联之间共享通用条件。

对于两个关系中都存在的条件,other中的条件将优先使用。若要查找两个关系的交集,请使用QueryMethods#and

# 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)         # discards the order condition
Post.order('id asc').only(:where, :order) # uses the specified order
# File activerecord/lib/active_record/relation/spawn_methods.rb, line 67
def only(*onlies)
  relation_with values.slice(*onlies)
end