Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails AR validates_uniqueness_of against polymorphic relationship

Is it posible to validate the uniqueness of a child model's attribute scoped against a polymorphic relationship?

For example I have a model called field that belongs to fieldable:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :name, :scope => :fieldable_id
end

I have several other models (Pages, Items) which have many Fields. So what I want is to validate the uniqueness of the field name against the parent model, but the problem is that occasionally a Page and an Item share the same ID number, causing the validations to fail when they shouldn't.

Am I just doing this wrong or is there a better way to do this?

like image 332
aaronrussell Avatar asked Mar 31 '10 21:03

aaronrussell


1 Answers

Just widen the scope to include the fieldable type:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :name, :scope => [:fieldable_id, :fieldable_type]
end
like image 65
Tony Fontenot Avatar answered Sep 28 '22 03:09

Tony Fontenot