跳至內文 跳至搜尋
方法
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)

若 `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!)

處理序會由合併評估

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