validates_uniqueness_of fails for String type in polymorphic associations #192

adamkangas opened this Issue Oct 7, 2011 · 7 comments


None yet

7 participants


I have a polymorphic Purchase model which is basically

class Purchase < ActiveRecord::Base
  belongs_to :user
  belongs_to :purchasable, :polymorphic => true

  # A user can only purchase each item once, keeping in mind that items of different purchasable_types may have the same ID
  validates :purchasable_id, :presence => true, :uniqueness => { :scope => [:user_id, :purchasable_type] } 

and then in my test:

it { should validate_uniqueness_of(:purchasable_id).scoped_to(:purchasable_type, :user_id) }

However this causes uninitialized constant Videp ... as the commentable_type in my factory is set to 'Video' and is being called...

Writing my own custom test for now.


I have the same problem here. Do you have a solution for this?

jfedick commented Jan 5, 2012

I am having the same problem.

travisp commented Jan 30, 2012

have the same problem here, tells me "uninitialized constant Collectioo" ... my model is named Collection.


I've just been rolling my own tests for these rare cases.

I doubt there's a good way to teach scoped_to to recognize our polymorphism unless we pass in additional data.

Perhaps scoped_to could be modified to take either symbols OR arrays. In my case I was allowing users to purchase either Videos or Documents.

Such a call might look like:

it { should validate_uniqueness_of(:purchasable_id).scoped_to([:purchasable_type, ["Video", "Document"]], :user_id) }

Where the second value in the array is either an array of possible values, or a range.

jasonong commented Feb 3, 2012

Same problem on my side.

TeaMoe commented Feb 3, 2012

I had the same problem, so I did a quick and dirty hack to shoulda-matchers which works for me.
You can find it in my fork at

let me know what you think

gabebw commented Mar 19, 2012

@TeaMoe: Can you file a pull request over at shoulda-matchers?

I'm closing this issue since it's a shoulda-matchers issue, not a shoulda issue.

@gabebw gabebw closed this Mar 19, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment