如何在 ActiveRecord 中查询 enum 字段的多个值? [英] How to query multi values of enum field in ActiveRecord?

查看:43
本文介绍了如何在 ActiveRecord 中查询 enum 字段的多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mymodel.rb

enum status: { posted: 1, failed: 2, suspended: 3 }

mycontroller.rb

mycontroller.rb

def filter_params
  params.fetch(:mymodel, {}).
  permit(
    :status => []
    )
end

我有像 mymodel[:status] => 这样的参数[失败",暂停"]

我如何通过状态获取所有结果是 failedsuspended

How can i get all results by status is failed and suspended

类似:Mymodel.where(status: filter_params[:status])

非常感谢!

当有电话时:

@mymodel = Mymodel.new(filter_params)

我收到此错误:

'["failed", "suspended"]' is not a valid status

推荐答案

在运行查询时,您需要为 enum 属性提供序号值.因此,您需要使用它们的整数值进行查询,而不是像 'failed''suspended' 这样的字符串.

When running a query, you need to supply the ordinal values for the enum attribute. So instead of strings like 'failed' or 'suspended', you need to query using their integer values.

幸运的是,您可以访问散列以轻松地将所有状态映射到 filter_params 散列中的整数:

Luckily, you can access a hash to easily map all the statuses to integers from your filter_params hash:

values = Mymodel.statuses.values_at(*Array(filter_params[:status]))

通过它,您可以运行查询以获取具有任何过滤状态的所有记录:

With that you can run your query to get all records which have any of the filtered statuses:

Mymodel.where(status: values)

不过,您不想将那段代码散布在各处,因此我建议您将其作为模型中的作用域来实现:

You don't want to scatter that piece of code all over the place though, so I recommend you'd implement this as a scope in your model:

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 或空数组.

Note that the return all if values.blank? line makes it possible to throw in nil or an empty array without breaking your query.

您现在可以轻松查询记录:

You can now easily query the records:

Mymodel.for_statuses(filter_params[:status])

请注意,您不能创建具有多个状态的记录.enum 只限制可以赋值的值,但是你只能赋值一个,否则你会得到 not a valid status 错误.

Note that you cannot create a record which has multiple statuses. enum only restricts the values that can be assigned, but you can assign only one, otherwise you get the not a valid status error.

请参阅Rails 文档,了解有关enum.

这篇关于如何在 ActiveRecord 中查询 enum 字段的多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆