This gem provides additional scopes for your ActiveRecord models.
Add this line to your application's Gemfile:
gem 'usefull_scopes'
Or install it yourself as:
$ gem install usefull_scopes
In order to use these scopes, we need to include UsefullScopes
module in our model.
class User < ActiveRecord::Base
include UsefullScopes
end
Name | Description |
---|---|
random | Fetches a random record |
exclude | Selects only those records who are not in a given array (you could also provide a single object as an argument) |
with | Returns records, where attributes' values are corresponding to a given hash. |
without | Returns records, where attributes' values are `NULL` or aren't equal to values from a given hash. |
These are the scopes created for each model's attribute.
Name | Description |
---|---|
by_attribute | Returns records ordered by `attribute` in descending order |
asc_by_attribute | Returns records ordered by `attribute` in ascending order |
like_by_attribute | Returns records, where attribute's value like a given term |
ilike_by_attribute | Сase insensitive implementation of `like_by_attribute` |
with_attribute | Returns records, where attribute's value is equal to a given value. Note: this scope is deprecated and will be removed in the following versions. Please, use `with` scope instead. |
without_attribute | Returns records, where attribute's value is `NULL`. Note: this scope is deprecated and will be removed in the following versions. Please, use `without` scope instead. |
Now, it is time to play with our model!
User.create([{name: 'Mike'}, {name: 'Paul'}])
user = User.random
user.name
=> 'Mike'
User.asc_by_name.map(&:name)
=> ['Mike', 'Paul']
User.by_name.map(&:name)
=> ['Paul', 'Mike']
users = User.with_name('Mike')
users.map(&:name)
=> ['Mike']
users = User.with(name: 'Mike')
=> SELECT "users".* FROM "users" WHERE ("users"."name" = 'Mike')
users.map(&:name)
=> ['Mike']
users = User.without(name: ['Mike', 'Paul'])
=> SELECT "users".* FROM "users" WHERE ("users"."name" NOT IN ('Mike','Paul'))
users
=> []
users = User.without(:name, :id)
=> SELECT "users".* FROM "users" WHERE ("users"."name" IS NULL AND "users"."id" IS NULL)
users.count
=> 2
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request