Repository is archived
No commit activity in last 3 years
No release in over 3 years
Adds methods to ActiveRecord for conditionally finding, creating, or updating records.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies
 Project Readme

find_or_create_on_scopes

Conditional creators for ActiveRecord

Author Tim Morgan
Version 1.2 (Sep 12, 2011)
License Released under the MIT license.

About

find_or_create_on_scopes adds handy find_or_create-type methods to ActiveRecord. You can use these methods to conditionally create, initialize, or update records depending on the presence of similar records. They work on your base model class and any scopes derived therefrom. (See Usage for examples.)

Installation

Important Note: This gem requires Ruby 1.9+. Ruby 1.8 is not and will never be supported.

To install, simply add the find_or_create_on_scopes gem to your Rails application's Gemfile:

gem 'find_or_create_on_scopes'

Usage

See the {FindOrCreateOnScopes} module documentation for the complete list of conditional creators/updaters. Some basic examples to give you an overview:

# Tries to find a user named 'riscfuture'. If such a User exists, returns it. If
# not, creates a user and sets its password to '123'.
User.where(login: 'riscfuture').find_or_create(password: '123')

# Tries to find a user named 'riscfuture'. If such a User exists, updates its
# password to '123'. If not, creates a new user and sets its password to '123'.
# Raises an exception if validation fails.
User.where(login: 'riscfuture').create_or_update!(password: '123')