Class: Predicates::Association

Inherits:
Base
  • Object
show all
Defined in:
lib/predicates/association.rb

Overview

Marks an attribute as being an association. Has options for controlling how many associated objects there can be.

You can require associations by name.

Example:

class Comment < ActiveRecord::Base
  has_one :owner
  owner_is_association :or_empty => true
end

Instance Attribute Summary collapse

Attributes inherited from Base

#full_message, #or_empty, #validate_if, #validate_on

Instance Method Summary collapse

Methods inherited from Base

#allow_empty?, #error, #error_binds, #initialize, #normalize, #to_human

Constructor Details

This class inherits a constructor from Predicates::Base

Instance Attribute Details

#maxObject

if there’s a maximum to the number of associated records



15
16
17
# File 'lib/predicates/association.rb', line 15

def max
  @max
end

#minObject

if there’s a minimum to the number of associated records



12
13
14
# File 'lib/predicates/association.rb', line 12

def min
  @min
end

Instance Method Details

#error_messageObject



17
18
19
# File 'lib/predicates/association.rb', line 17

def error_message
  @error_message || :required
end

#validate(value, record) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/predicates/association.rb', line 21

def validate(value, record)
  # we treat singular and plural the same
  associated = [value].flatten

  # we need to check the validity of new records in order to calculate how many
  # will save properly. this lets us validate against the min/max parameters.
  invalid_new_records = associated.select{|r| r.new_record? and not r.valid?}
  valid_new_records = associated - invalid_new_records

  valid = true

  # then validate against min/max
  quantity = valid_new_records.length
  valid &&= (!min or quantity >= min)
  valid &&= (!max or quantity <= max)

  # if we can't allow empty associations, then we need to do an extra check: if these
  # records are new and invalid then they might not persist.
  valid &&= (allow_empty? or quantity > 0)

  valid
end