Topic: Validate uniqueness with scope has_one :through

Hi,
I am having trouble validating  the uniqueness of a field based on the scope of a related field

This is the code I used, but I can't get it working

http://pastebin.com/dwZ1jBrz

What am I missing?

Cheers!

Re: Validate uniqueness with scope has_one :through

Looking at the Rails source code for the UniquenessValidator it looks likes the values for scope can only be columns in the db for that model or a belongs_to association. For the belongs_to association it reflections on the association and basically uses the foreign_key. So this would work:

class Element < ActiveRecord::Base
  belongs_to  :order
  has_one     :type_of_element, :through =>  :pedido
  validates   :serial_number, :uniqueness  => {:scope => :order} 
end

or

class Element < ActiveRecord::Base
  belongs_to  :order
  has_one     :type_of_element, :through =>  :pedido
  validates   :serial_number, :uniqueness  => {:scope => :order_id} 
end

I could be totally wrong about this though. Of course neither of those examples would provide the same end outcome you are looking for.

Last edited by themusicman (2012-05-17 15:37:26)

Re: Validate uniqueness with scope has_one :through

Thank you! I thought it was possible.

What I am going to to do is to have a type_element_id colum and update that colum on the controller based on order relationship.

Cheers!