通过 Arel 组合活动记录上的不同条件

问题描述 投票:0回答:1

我有一个表 SubscriberProperty,其中包含列(名称、类型、account_id、类别、掩码、联系人、模式)

我如何在表上写一个 Arel 条件,该条件考虑用户输入,例如如果用户输入了名称,那么我应该过滤名称,否则不

subs = SubscriberPropertyType.arel_table
SubscriberProperty.where(sub[:name].eq(name))

如果用户已进入模式,那么它也应该按模式进行过滤

mode = {mode entered by user}
SubscriberProperty.where(sub[:mode].eq(mode))

我如何根据用户是否输入特定字段的事实来组合以上两个条件

ruby-on-rails ruby arel
1个回答
0
投票

你可以继续链接你的条件,如果这是在控制器中,我通常这样做:

name = params[:name]
mode = params[:mode]

scope = SubscriberProperty.all
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.all
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
© www.soinside.com 2019 - 2024. All rights reserved.