Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for PostgreSQL ENUM #44

Open
ledermann opened this issue Feb 22, 2019 · 3 comments
Open

Support for PostgreSQL ENUM #44

ledermann opened this issue Feb 22, 2019 · 3 comments

Comments

@ledermann
Copy link

Great gem, @mrkamel!

One small thing: Support for PostgreSQL enums would be great. Currently, it fails with a NameError. Example:

CREATE TYPE public.person_gender AS ENUM (
    'male',
    'female'
);

CREATE TABLE public.people (
    id bigint NOT NULL,
    name character varying,
    gender public.person_gender
);
class Person < ApplicationRecord
  include SearchCop

  enum gender: {
    male: 'male',
    female: 'female'
  }

  search_scope :search do
    attributes :gender, :name
  end
end

Person.search("gender:male")
=> NameError: Uninitialized constant SearchCopGrammar::Attributes::Enum
@ledermann
Copy link
Author

ledermann commented Feb 22, 2019

Maybe this code (placed in an initializer) can be used as a workaround:

module SearchCopGrammar
  module Attributes
    class Enum < Base
      def matches(value)
        eq value
      end
    end
  end
end

module SearchCop
  module Visitors
    class Visitor
      def visit_enum(attribute)
        "CAST(#{quote_table_name attribute.table_alias}.#{quote_column_name attribute.column_name} AS VARCHAR)"
      end

      alias visit_SearchCopGrammar_Attributes_Enum visit_enum
    end
  end
end

@mrkamel
Copy link
Owner

mrkamel commented Feb 23, 2019

hi, thanks for opening this.
Actually, i want to stay as database agnostic as possible.
But more importantly, it's currently not possible to add database specific attributes.
While postgres and mysql have an ENUM which works in a very similar way, sqlite doesn't have one afaik, and if they add one, it could probably work differently.

@westonganger
Copy link

westonganger commented Apr 22, 2022

Looks like you can use Custom Operators for this

enum gender: {
  male: 0,
  female: 1,
}

search_scope :search do
  attributes :gender

  generator :match_gender_enum do |column_name, raw_value|
    gender_int = genders[raw_value]
    "#{column_name} = #{gender_int}"
  end
end

Book.search(gender: {match_gender_enum: "male"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants