Created
July 13, 2023 23:02
-
-
Save lucasmazza/77f86d00b2f7417a92921b873cbfedf5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProductSearch < ScopeBuilder::Scope | |
param :name, :string | |
param :category, :integer | |
param :status, :string | |
order_by :name, :created_at | |
private | |
def apply_name_param(scope, value) | |
scope.search_by_name(value) | |
end | |
def apply_category_param(scope, value) | |
scope.where(category_id: value) | |
end | |
def apply_status_param(scope, value, context) | |
scope.where(status: value) if context[:user].admin? | |
end | |
def prepare(scope, params, context) | |
scope.where('deleted_at IS NULL') | |
end | |
end | |
scope = ProductSearch.new(Product, user: user) | |
result = scope.build(name: "iPhone", status: "available", order: ["name", "created_at"], dir: "desc") | |
# result.valid? # => true | false | |
# result.errors # => ActiveModel::Errors | |
# result.params # => ProductSearch::Params | |
render json: { data: result.scope } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment