Filterable By
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 |scope, value|
scope.joins(:posts).where(:"posts.author_id" => value)
end
end
Comment.filter_by(params[:filter]) # => ActiveRecord::Relation
Simple use cases:
Comment.filter_by({ "post_id" => "1" })
# => WHERE post_id = 1
Comment.filter_by({ "user_id" => "2", "ignored" => "3" })
# => WHERE user_id = 2
Comment.filter_by({ "post_author_id" => "5" })
# => JOINS posts ON posts.id = comments.post_id WHERE posts.author_id = 5