validates_uniqueness_of fails for String type in polymorphic associations #192

Closed
adamkangas opened this Issue Oct 7, 2011 · 7 comments

Projects

None yet

7 participants

@adamkangas

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] } 
end

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 commentable_type.next is being called...

Writing my own custom test for now.

@brunoald

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

@jfedick
jfedick commented Jan 5, 2012

I am having the same problem.

@travisp
travisp commented Jan 30, 2012

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

@adamkangas

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
jasonong commented Feb 3, 2012

Same problem on my side.

@TeaMoe
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 https://github.com/TeaMoe/shoulda-matchers

let me know what you think

@gabebw
Member
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