Rails AR validates_uniqueness_of against polymorphic relationship
Asked Answered
C

2

10

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?

Cart answered 31/3, 2010 at 21:27 Comment(0)
R
22

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
Rema answered 31/3, 2010 at 21:47 Comment(1)
Thank you. Simples when you know how :)Cart
M
0

You can also add a message to override the default message, or use scope to add the validation:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :fieldable_id, :scope => [:fieldable_id, :fieldable_type], :message => 'cannot be duplicated'
end

As a bonus if you go to your en.yml, and enter:

  activerecord:
    attributes:
     field:
       fieldable_id: 'Field'

You are going to replace the default 'subject' that rails add to the errors with the one you specify here. So instead of saying: Fieldable Id has been already taken or so, it would say:

 Field cannot be duplicated
Mccutcheon answered 10/6, 2016 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.