How to request multiple enum field values ​​in ActiveRecord?

mymodel.rb

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

mycontroller.rb

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

And I have options like mymodel[:status] => ["failed", "suspended"]

How can I get all the results by status failedandsuspended

Sort of: Mymodel.where(status: filter_params[:status])

Thank you so much!

And when the call:

@mymodel = Mymodel.new(filter_params)

I got this error:

'["failed", "suspended"]' is not a valid status
+4
source share
2 answers

When executing the query, you need to specify the ordinal values ​​of the enum attribute. Therefore, instead of strings such as 'failed'or 'suspended', you need to request their integer values.

Fortunately, you can access the hash to easily map all statuses to integers from the hash filter_params:

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

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

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 . Rails.

+8

Rails 5 , :

Mymodel.where(status: ['failed', 'suspended'])

:

statuses = filter_params[:status].map(&:to_sym)
Mymodel.where(status: statuses)
+3

All Articles