Module: ActiveModel::Associations::ClassMethods

Defined in:
lib/active_model/associations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(name, scope = nil, options = {}) ⇒ Object

define association like ActiveRecord



24
25
26
27
# File 'lib/active_model/associations.rb', line 24

def belongs_to(name, scope = nil, options = {})
  reflection = ActiveRecord::Associations::Builder::BelongsTo.build(self, name, scope, options)
  ActiveRecord::Reflection.add_reflection self, name, reflection
end

#has_many(name, scope = nil, options = {}, &extension) ⇒ Object

define association like ActiveRecord



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/active_model/associations.rb', line 30

def has_many(name, scope = nil, options = {}, &extension)
  options.reverse_merge!(active_model: true, target_ids: "#{name.to_s.singularize}_ids")
  if scope.is_a?(Hash)
    options.merge!(scope)
    scope = nil
  end

  reflection = ActiveRecord::Associations::Builder::HasManyForActiveModel.build(self, name, scope, options, &extension)
  ActiveRecord::Reflection.add_reflection self, name, reflection

  mixin = generated_association_methods
  mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def #{options[:target_ids]}=(other_ids)
      @#{options[:target_ids]} = other_ids
      association(:#{name}).reset
      association(:#{name}).reset_scope
      @#{options[:target_ids]}
    end
  CODE
end