Module: Ardm::ActiveRecord::Associations::ClassMethods

Defined in:
lib/ardm/active_record/associations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(field, *args) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/ardm/active_record/associations.rb', line 68

def belongs_to(field, *args)
  options = args.shift || {}

  if String === options || Class === options # belongs_to :name, 'Class', options: 'here'
    options = (args.last || {}).merge(:model => options.to_s)
  end

  unless Hash === options
    raise ArgumentError, "bad belongs_to #{field} options format #{options.inspect}"
  end

  options.delete(:default)
  options.delete(:required)
  opts = Ardm::ActiveRecord::Associations.convert_options(self, options)
  super field, *opts
  assoc = reflect_on_association(field)
  Ardm::ActiveRecord::Record.on_finalize << lambda do
    self.class_eval do
      property assoc.foreign_key, assoc.klass.key.first.class, key: false
    end
  end
  nil
end

#dump_associations_hash(options) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ardm/active_record/associations.rb', line 50

def dump_associations_hash(options)
  options.inject({}) do |new_attrs, (key, value)|
    if reflection = reflect_on_association(key.to_sym)
      if value.is_a?(ActiveRecord::Base)
        new_attrs[reflection.foreign_key] = value.id
        if reflection.respond_to?(:polymorphic?) && reflection.polymorphic?
          new_attrs[reflection.foreign_type] = value.class.base_class
        end
      else
        new_attrs[reflection.foreign_key] = value
      end
    else
      new_attrs[key] = value
    end
    new_attrs
  end
end

#has(count, name, *args) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/ardm/active_record/associations.rb', line 96

def has(count, name, *args)
  options = args.shift || {}

  if String === options || Class === options # has n, :name, 'Class', options: 'here'
    options = (args.last || {}).merge(:model => options.to_s)
  end

  unless Hash === options
    raise ArgumentError, "bad has #{count} options format #{options.inspect}"
  end

  options[:order] = Ardm::ActiveRecord::Query.order(self, options[:order]) if options[:order]
  opts = Ardm::ActiveRecord::Associations.convert_options(self, options, :through, :order)

  if Ardm.rails3?
    case count
    when 1      then has_one  name, *opts
    when "many" then has_many name, *opts
    end
  else
    case count
    when 1      then has_one  name, *opts
    when "many" then has_many name, *opts
    end
  end
end

#nObject



92
93
94
# File 'lib/ardm/active_record/associations.rb', line 92

def n
  "many"
end