如何在 ActiveRecord 中查询枚举字段的多个值?
How to query multi values of enum field in ActiveRecord?
mymodel.rb
enum status: { posted: 1, failed: 2, suspended: 3 }
mycontroller.rb
def filter_params
params.fetch(:mymodel, {}).
permit(
:status => []
)
end
我有像 mymodel[:status] => ["failed", "suspended"]
这样的参数
如何按状态获取所有结果 failed
和 suspended
类似于:Mymodel.where(status: filter_params[:status])
非常感谢!
而当来电时:
@mymodel = Mymodel.new(filter_params)
我收到这个错误:
'["failed", "suspended"]' is not a valid status
当运行查询时,您需要为枚举属性提供序号值。因此,您需要使用它们的整数值进行查询,而不是像 'failed'
或 'suspended'
这样的字符串。
幸运的是,您可以访问散列以轻松地将所有状态映射到 filter_params
散列中的整数:
values = Mymodel.statuses.values_at(*Array(filter_params[:status]))
有了它,您可以 运行 您的查询以获取具有任何过滤状态的所有记录:
Mymodel.where(status: values)
虽然您不想将那段代码分散到各处,所以我建议您将其实现为模型中的一个范围:
class Mymodel < ActiveRecord::Base
enum status: { posted: 1, failed: 2, suspended: 3 }
scope :for_statuses, ->(values) do
return all if values.blank?
where(status: statuses.values_at(*Array(values)))
end
end
请注意,return all if values.blank?
行可以在不中断查询的情况下输入 nil
或空数组。
您现在可以轻松查询记录:
Mymodel.for_statuses(filter_params[:status])
请注意,您不能创建具有多个状态的记录。 enum
只限制可以赋值的值,但是你只能赋值一个,否则会报not a valid status
错误。
有关 enum
的更多信息,请参阅 the Rails documentation。
在 Rails 5 中,您现在可以将字符串数组传递给查询,例如:
Mymodel.where(status: ['failed', 'suspended'])
对于早期版本,只需将数组值转换为符号即可:
statuses = filter_params[:status].map(&:to_sym)
Mymodel.where(status: statuses)
mymodel.rb
enum status: { posted: 1, failed: 2, suspended: 3 }
mycontroller.rb
def filter_params
params.fetch(:mymodel, {}).
permit(
:status => []
)
end
我有像 mymodel[:status] => ["failed", "suspended"]
如何按状态获取所有结果 failed
和 suspended
类似于:Mymodel.where(status: filter_params[:status])
非常感谢!
而当来电时:
@mymodel = Mymodel.new(filter_params)
我收到这个错误:
'["failed", "suspended"]' is not a valid status
当运行查询时,您需要为枚举属性提供序号值。因此,您需要使用它们的整数值进行查询,而不是像 'failed'
或 'suspended'
这样的字符串。
幸运的是,您可以访问散列以轻松地将所有状态映射到 filter_params
散列中的整数:
values = Mymodel.statuses.values_at(*Array(filter_params[:status]))
有了它,您可以 运行 您的查询以获取具有任何过滤状态的所有记录:
Mymodel.where(status: values)
虽然您不想将那段代码分散到各处,所以我建议您将其实现为模型中的一个范围:
class Mymodel < ActiveRecord::Base
enum status: { posted: 1, failed: 2, suspended: 3 }
scope :for_statuses, ->(values) do
return all if values.blank?
where(status: statuses.values_at(*Array(values)))
end
end
请注意,return all if values.blank?
行可以在不中断查询的情况下输入 nil
或空数组。
您现在可以轻松查询记录:
Mymodel.for_statuses(filter_params[:status])
请注意,您不能创建具有多个状态的记录。 enum
只限制可以赋值的值,但是你只能赋值一个,否则会报not a valid status
错误。
有关 enum
的更多信息,请参阅 the Rails documentation。
在 Rails 5 中,您现在可以将字符串数组传递给查询,例如:
Mymodel.where(status: ['failed', 'suspended'])
对于早期版本,只需将数组值转换为符号即可:
statuses = filter_params[:status].map(&:to_sym)
Mymodel.where(status: statuses)