Module: EacRailsUtils::Models::TablelessAssociations::ClassMethods

Defined in:
lib/eac_rails_utils/models/tableless_associations.rb

Instance Method Summary collapse

Instance Method Details

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

define association like ActiveRecord



25
26
27
28
# File 'lib/eac_rails_utils/models/tableless_associations.rb', line 25

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



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

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