Skip to content

Avoid issues when using the gem with ActiveQuery and first_or_create by using StripAttributes.strip

Greg Dowling edited this page Jan 23, 2015 · 4 revisions

Strip attributes does its magic as the attributes in your model are saved.

Using ActiveRecord if you create a query, and then do first_or_create you can get some unexpected results if you use unstripped strings.

For example with the model:-

class Contact < ActiveRecord::Base
   validates_uniqueness_of :name
   strip_attributes only: [:name], collapse_spaces: true
end

The following code will create a duplicate contact

name = '   My    Name   '
contact1 = Contact.where(name: name).first_or_create # contact1.name == 'My Name'
contact2 = Contact.where(name: name).first_or_create # contact2 <> contact1,  contact2.valid? == false 

The issue is that the name string isn't stripped when the query is executed - so the matching record isn't found.

You can avoid the issue by [stripping your query strings] (https://github.com/rmm5t/strip_attributes#using-it-directly)

name = StripAttributes.strip('   My    Name   ', :collapse_spaces => true) # name = 'My Name'
contact1 = Contact.where(name: name).first_or_create # contact1.name == 'My Name'
contact2 = Contact.where(name: name).first_or_create # contact2 == contact1 

Note that strip_attributes strips a variety of unusual characters, so .squeeze(' ').strip isn't enough on its own