Skip to content


Subversion checkout URL

You can clone with
Download ZIP


validates_uniqueness_of fails for String type in polymorphic associations #192

adamkangas opened this Issue · 7 comments

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?


I am having the same problem.


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.


Same problem on my side.


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


@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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.