Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on an ActiveModel Object, how do I check uniqueness?

In Bryan Helmkamp's excellent blog post called "7 Patterns to Refactor Fat ActiveRecord Models", he mentions using Form Objects to abstract away multi-layer forms and stop using accepts_nested_attributes_for.

Edit: see below for a solution.

I've almost exactly duplicated his code sample, as I had the same problem to solve:

class Signup
  include Virtus

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attr_reader :user
  attr_reader :account

  attribute :name, String
  attribute :account_name, String
  attribute :email, String

  validates :email, presence: true
  validates :account_name,
    uniqueness: { case_sensitive: false },
    length: 3..40,
    format: { with: /^([a-z0-9\-]+)$/i }

  # Forms are never themselves persisted
  def persisted?
    false
  end

  def save
    if valid?
      persist!
      true
    else
      false
    end
  end

private

  def persist!
    @account = Account.create!(name: account_name)
    @user = @account.users.create!(name: name, email: email)
  end
end

One of the things different in my piece of code, is that I need to validate the uniqueness of the account name (and user e-mail). However, ActiveModel::Validations doesn't have a uniqueness validator, as it's supposed to be a non-database backed variant of ActiveRecord.

I figured there are three ways to handle this:

  • Write my own method to check this (feels redundant)
  • Include ActiveRecord::Validations::UniquenessValidator (tried this, didn't get it to work)
  • Or add the constraint in the data storage layer

I would prefer to use the last one. But then I'm kept wondering how I would implement this.

I could do something like (metaprogramming, I would need to modify some other areas):

  def persist!
    @account = Account.create!(name: account_name)
    @user = @account.users.create!(name: name, email: email)
  rescue ActiveRecord::RecordNotUnique
    errors.add(:name, "not unique" )
    false
  end

But now I have two checks running in my class, first I use valid? and then I use a rescue statement for the data storage constraints.

Does anyone know of a good way to handle this issue? Would it be better to perhaps write my own validator for this (but then I'd have two queries to the database, where ideally one would be enough).

like image 953
JeanMertz Avatar asked Feb 03 '13 07:02

JeanMertz


People also ask

What are validations in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.


1 Answers

Creating a custom validator may be overkill if this just happens to be a one-off requirement.

A simplified approach...

class Signup

  (...)

  validates :email, presence: true
  validates :account_name, length: {within: 3..40}, format: { with: /^([a-z0-9\-]+)$/i }

  # Call a private method to verify uniqueness

  validate :account_name_is_unique


  def persisted?
    false
  end

  def save
    if valid?
      persist!
      true
    else
      false
    end
  end

  private

  # Refactor as needed

  def account_name_is_unique
    if Account.where(name: account_name).exists?
      errors.add(:account_name, 'Account name is taken')
    end
  end

  def persist!
    @account = Account.create!(name: account_name)
    @user = @account.users.create!(name: name, email: email)
  end
end
like image 195
crftr Avatar answered Sep 25 '22 08:09

crftr