9

2 つの関係をどのように追加しますか? + 演算子を試すと、配列が返されます。しかし、関係を返すために必要です。

ありがとう、マイク

4

3 に答える 3

8

試す:

new_relation = relation.merge(another_relation)
于 2012-09-06T04:37:46.943 に答える
3

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

于 2014-03-01T18:59:09.483 に答える
2

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 オブジェクトを返します。

于 2013-05-25T01:27:29.087 に答える