Thursday, August 11, 2011

"undefined method `text?' for nil:NilClass" when using :uniqueness validator

Short answer: if your validation line says this ...

... then change it to reference column name instead of association name like this ...

... and you're all set! Have a good day.

For an explanation of why this happens, read these steps I used to re-create ("..." denotes output I didn't paste in here):





I threw a debugger call into active_record's uniqueness.rb file:

and dove back into the console

now line 57 is making sense

back to tagging.rb:

... and it works!


  1. Except it does the same thing on an alias_attribute. How do you get around it there? You are most likely aliases it for a reason. In my case it's because I don't want to expose the underlying name in our API. The crappy part is even if I use RABL to change the name for input/output, it still forces me to use the non-aliased name on the validation and when it throws an error it uses the non-aliased name in the error.

    This is leaving me to doing really crappy things like inspecting my result for errors with an after_save and replacing the error values with the aliased attribute names.. which stinks.

  2. Thank you! This is still a issue with Rails 3.1.3.

  3. Thanks Luke, this helped me a lot. I'm new to Rails and was having a great time getting my bearings with TDD, FactoryGirl, etc. until I ran head-first into this issue. Cheers!

  4. As a side note. This technique means you have to instantiate the related objects so there is no getting away from hitting the DB in your test.

    e.g. I had to use let!(:something){FactoryGirl.create(:something)} instead of let(:something)


about this blog:

I am a self-taught Ruby on Rails programmer, so I depend on the community-of-strangers that is the Internet for so many little bits of information. This blog is here for one purpose: to save you five minutes at a time by giving you a solution or answering a question that took me more than five minutes to figure out.

The format is intended to be incredibly simple:
Given a certain context A
When I run into problem B
Then I get past it by doing C

The name? That refers to the ten postulates that form the foundation of Euclid's geometry. Basically I just like the sound of the name.

My other websites:

Search This Blog