Skip to content

Instantly share code, notes, and snippets.

@nglx
Last active December 24, 2015 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nglx/6859123 to your computer and use it in GitHub Desktop.
Save nglx/6859123 to your computer and use it in GitHub Desktop.
class UsersController < ApplicationController
def index
user_search = UserSearch.new(params[:user_search])
@users = User.by_user_search(user_search)
end
end
# user search form object
class UserSearch
include Virtus.model
attribute :name, String
attribute :rating, Integer, default: 4 # setting default values
attribute :skills, ArrayFromCommaSeparatedString # parsing parameters
end
class User < ActiveRecord::Base
scope :by_user_search, ->(user_search) {
scopes = []
scopes << where('name like ?', "%#{user_search.name}%") if user_search.name
scopes << where('rating > ?', rating)
scopes << tagged_with(user_search.skills, any: true) if user_search.skills
scopes.inject(User.all) { |r,e| r.merge(e) }
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment