2 つの関係をどのように追加しますか? + 演算子を試すと、配列が返されます。しかし、関係を返すために必要です。
ありがとう、マイク
試す:
new_relation = relation.merge(another_relation)
Arel Constraints を使用して 2 つの ActiveRecord::Relation を追加できます
constraints_1 = Model.matching_one.arel.constraints
constraints_2 = Model.matching_two.arel.constraints
Model.where(constraints_1.and(constraints_2)).class => ActiveRecord::Relation
or 演算子も使用できます
Model.where(constraints_1.or(constraints_2)).class => ActiveRecord::Relation
実際の例
constraints_1 = User.where(id: 1..5).arel.constraints
constraints_2 = User.where('id != 2').arel.constraints
User.where(constraints_1.and(constraints_2))
それについての優れたスクリーンキャストを見ることができますhttp://railscasts.com/episodes/355-hacking-with-arel
ActiveRecord::Relation オブジェクトを追加して、'AND' ではなく 'OR' の結果を取得する場合 (連鎖によって 'AND' の動作が得られます)、適切に再生するには結果が ActiveRecord::Relation である必要があります。他のコード (meta_search など)...
def matching_one_or_two
temp = Model.matching_one + Model.matching_two
Model.where('id in (?)',temp.map(&:id))
end
確かに世界最高のパフォーマンスではありませんが、「OR」の結果を指す ActiveRecord::Relation オブジェクトになります。
また、Rails に "OR" を生成するように依頼するのではなく、"OR" を直接 sql に挿入して、データベース アプリケーションのパフォーマンスを向上させることもできます。一例:
Model.where("table_name.col = 'one' OR table_name.col = 'two'")
これも ActiveRecord::Relation オブジェクトを返します。