rails-has-valid gem

Partial validation of ActiveRecord objects in Ruby on Rails 4+ made simple.

Usage

gem 'rails-has-valid', '0.0.0'
# user.rb
        class User < ActiveRecord::Base
                # ...
                        VALIDATE_ATTRIBUTES = {
                                create: [:email, :subscribed],
                                update: create.concat([:password])
                        }
                # ...
        end
# users_controller.rb
        user = User.new

        #
        # validate given attributes only
        #
        user.has_valid?(User::VALIDATE_ATTRIBUTES[:create])
        # => true

        #
        # save object if given parameters are valid
        # return false otherwise
        #
        user.save_if_has_valid(User::VALIDATE_ATTRIBUTES[:update])

        #
        # save object if given parameters are valid
        # raise ActiveRecord::RecordInvalid exception otherwise
        #
        user.save_if_has_valid!(User::VALIDATE_ATTRIBUTES[:update])     

        #
        # update object attributes to given values if given attributes are valid
        # return false otherwise
        #
        user.update_attributes_if_has_valid( { email: 'new@email.com' }, User::VALIDATE_ATTRIBUTES[:update])

        #
        # update object attributes to given values if given attributes are valid
        # raise ActiveRecord::RecordInvalid exception otherwise
        #
        user.update_attributes_if_has_valid!( { email: 'new@email.com' }, User::VALIDATE_ATTRIBUTES[:update])

It’s been tested with Rails 4.1+ only but will most likely work with Rails 3+ as well.

Contributing to rails-has-valid

Copyright © 2014 Juraj Masar. See LICENSE.txt for further details.