Class: Morpheus::Mixins::Associations::HasOneAssociation

Inherits:
Association
  • Object
show all
Defined in:
lib/morpheus/mixins/associations/has_one_association.rb

Instance Method Summary collapse

Methods inherited from Association

#id, #includes, #nil?, #to_param, #try

Constructor Details

#initialize(owner, association, settings = {}) ⇒ HasOneAssociation

The initializer calls out to the superclass’ initializer and then sets the options particular to itself.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/morpheus/mixins/associations/has_one_association.rb', line 8

def initialize(owner, association, settings = {})
  super

  # The foreign key is used to generate the url for the association
  # request when the association is transformed into a relation.
  # The default is to use the class of the owner object with an '_id'
  # suffix.
  @options[:foreign_key] ||= "#{@owner.class.to_s.underscore}_id".to_sym

  # The primary key is used in the generated url for the target. It
  # defaults to :id.
  @options[:primary_key] ||= :id

  # @association_class stores the class of the association, constantized
  # from the named association (i.e. Automobile, Car, CarClub)
  if @options[:class_name]
    @association_class = @options[:class_name].constantize
  else
    @association_class = @association
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Morpheus::Mixins::Associations::Association

Instance Method Details

#load_target!Object

When loading the target, the primary key is first checked. If the key is nil, then an nil is returned. Otherwise, the target is requested at the generated url. For a has_one :meeting association on a class called Course, the generated url might look like this: /meetings?course_id=1, where the 1 is the primary key.



39
40
41
42
43
# File 'lib/morpheus/mixins/associations/has_one_association.rb', line 39

def load_target!
  if primary_key = @owner.send(@options[:primary_key])
    Relation.new(@association_class.to_s.classify.constantize).where(@options[:foreign_key] => primary_key).limit(1).first
  end
end

#with_filter(filter) ⇒ Object



30
31
32
# File 'lib/morpheus/mixins/associations/has_one_association.rb', line 30

def with_filter(filter)
  HasOneAssociation.new(@owner, @association, :target => @target, :filters => @filters.dup.push(filter), :options => @options)
end