Home > Net >  Scope for multiple filters
Scope for multiple filters

Time:08-03

I'm new to Rails and I'm using Google Translate to post.

I currently have this filter, however, it filters only one item from public_sphere, how do I make it a multiple filter, in this case, the user can select more than one option from public_sphere.

        scope :filter_public_sphere, -> (params) {
          params[:public_sphere].present? ?
            where(
              "public_sphere = ?", 
              AtaPublic.public_spheres[params[:public_sphere]]
            )
          :
            all
        }

In this case, the API must receive an array instead of a value. For that, what would my filter look like?

CodePudding user response:

Arel should do the work for you. If you have a where clause in the form where(attribute: [array of attribute values]) it will generate an IN clause for the SQL

scope :filter_public_sphere, -> (params) {
  params[:public_sphere].present? ?
    where(
      public_sphere: AtaPublic.public_spheres[params[:public_sphere]]
    )
  :
    all
}

Assuming AtaPublic.public_spheres[params[:public_sphere]] returns an array of "public_sphere" identifiers.

  • Related