Git Product home page Git Product logo

filterable-by's Introduction

Filterable By

Test

ActiveRecord plugin to parse e.g. a filter query parameter apply scopes. Useful for JSON-API compatibility.

Installation

Add gem 'filterable-by' to your Gemfile.

Usage

class Comment < ActiveRecord::Base
  belongs_to :post

  filterable_by :post_id, :user_id
  filterable_by :post_author_id do |value|
    joins(:posts).where(:'posts.author_id' => value)
  end
  filterable_by :only do |value, **opts|
    case value
    when 'mine'
      where(user_id: opts[:user_id]) if opts[:user_id]
    else
      all
    end
  end
end

Comment.filter_by(params[:filter], user_id: current_user.id)  # => ActiveRecord::Relation

Simple use cases:

Comment.filter_by({ 'post_id' => '1' })
# => WHERE post_id = 1

Comment.filter_by({ 'post_id' => ['1', '2'] })
# => WHERE post_id IN (1, 2)

Comment.filter_by({ 'post_id_not' => '3' })
# => WHERE post_id != 3

Comment.filter_by({ 'user_id' => '2', 'ignored' => '3' })
# => WHERE user_id = 2

Comment.filter_by({ 'only' => 'mine' }, user_id: 4)
# => WHERE user_id = 4

Comment.filter_by({ 'post_author_id' => '5' })
# => JOINS posts ON posts.id = comments.post_id WHERE posts.author_id = 5

filterable-by's People

Contributors

dependabot[bot] avatar dim avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.