2

I want to limit my association to two (one of every scope). I tried:

has_many :associations
has_many :associations_with_first_scope, :class_name => 'Association', :conditions => {...}
has_many :associations_with_second_scope, :class_name => 'Association', :conditions => {...}

validates :associations, {:maximum => 4}
validates :associations_with_first_scope, {:maximum => 2}
validates :associations_with_second_scope, {:maximum => 2}

and I also tried custom validator (i tried count, size and length also):

validate :custom_associations_limit

def custom_associations_limit
  error.add(:base, '...') if associations_with_first_scope.size > 2
  error.add(:base, '...') if associations_with_second_scope.size > 2
end

I also tried to put validation into association model. Nothing works. I think my problem caused by using nested_form gem. When I have form with four associations (two of each kind) and I'll delete tow and add tow, model thinks it has six associations instead of four. Because it is validating probably before nested_attributes are passed (with allow_destroy set to true).

Any can help with this?

retro
  • 3,765
  • 2
  • 20
  • 37
  • possible duplicate of [Validate max amount af associated objects](http://stackoverflow.com/questions/1270663/validate-max-amount-af-associated-objects) – Peter Brown Aug 15 '12 at 12:38

1 Answers1

0

Rails already has this built-in with the has_one macro.

has_many :associations
has_one :associations_with_first_scope, :class_name => 'Association', :conditions => {...}
has_one :associations_with_second_scope, :class_name => 'Association', :conditions => {...}

The only difference is that you won't be using a plural association since there will only ever be one.

Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • I know. But limiting for one is now temporary. It will be pure has_many soon. I need to dynamically adds end remove associations in my form. Same problem is for maximum 4, and limiting scopes to 2. – retro Aug 15 '12 at 12:14
  • Why not just start with has_one and change it to has_many when you need it? It seems like you're over complicating the problem. – Peter Brown Aug 15 '12 at 12:16
  • I need it for has_many. I'm testing it locally. Let's say I really need maximum 4 and for every scope max 2. I'm going to update my question. – retro Aug 15 '12 at 12:18
  • If you need to limit to something other than one, you should use has_many through and use the join model to do the validation. – Peter Brown Aug 15 '12 at 12:19
  • Why this approach works when you're not using nested_form for dynamical forms? And I think there is no difference. I'll just use same methods but with one more model. – retro Aug 15 '12 at 12:20
  • Check out the link I posted as a duplicate. I think using count instead of size might make it work. – Peter Brown Aug 15 '12 at 12:38
  • I think this is not duplicate. I tried all - count, size and length. – retro Aug 15 '12 at 12:41