Arel を介してアクティブ レコード上のさまざまな条件を組み合わせる
概要
列 (name、type、account_id、category、mask、contact、mode) を持つテーブル SubscriberProperty があります。
ユーザーが名前を入力した場合は名前でフィルターする必要がある、そうでない場合はフィルターしないなど、ユーザー入力を考慮する Arel 条件をテーブルに記述するにはどうすればよいですか?
subs = SubscriberPropertyType.arel_table
SubscriberProperty.where(sub[:name].eq(name))
ユーザーがモードに入っている場合は、モードでもフィルタリングする必要があります
mode = {mode entered by user}
SubscriberProperty.where(sub[:mode].eq(mode))
ユーザーが特定のフィールドに入力したかどうかに依存するという事実に基づいて、上記の 2 つの条件を組み合わせるにはどうすればよいですか?
解決策
条件を連鎖し続けることができます。これがコントローラー内にある場合、私は通常次のようにします。
name = params[:name]
mode = params[:mode]
scope = SubscriberProperty.joins(:subscriber_property_type)
scope = scope.where(subscriber_property_type: {name:}) if name
scope = scope.where(subscriber_property_type: {mode:}) if mode
@subscriber_properties = scope
Arel は不要に思えますが、まったく同じロジックであり、eq 以外の演算子を使用する予定がある場合に役立つ可能性があります。
scope = SubscriberProperty.joins(:subscriber_property_type)
type = SubscriberPropertyType.arel_table
scope = scope.where(type[:name].eq(name)) if name
scope = scope.where(type[:mode].eq(mode)) if mode
@subscriber_properties = scope