Module: MissHannigan::ClassMethods

Defined in:
lib/miss_hannigan/miss_hannigan.rb

Instance Method Summary collapse

Instance Method Details

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



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/miss_hannigan/miss_hannigan.rb', line 6

def has_many(name, scope = nil, **options, &extension) 
  nullify_then_purge = false

  # we're really just relying on :nullify. so just return our dependent option to that
  if options[:dependent] == :nullify_then_purge
    nullify_then_purge = true
    options[:dependent] = :nullify
  end

  # get our normal has_many reflection to get setup
  reflection = super

  if nullify_then_purge

    # has the details of the relation to Child
    reflection_details = reflection[name.to_s]

    # I bet folks are going to forget to do the migration of foreign_keys to accept null. Rails defaults 
    # to not allow null.
    if !reflection_details.klass.columns.find { |c| c.name == reflection_details.foreign_key }.null
      raise "The foreign key must be nullable to support MissHannigan. You should create a migration to: 
        change_column_null :#{name.to_s}, :#{reflection_details.foreign_key}, true"
    end
    
    after_destroy do |this_object|
      CleanupJob.perform_later(reflection_details.klass.to_s, reflection_details.foreign_key)
    end
  end

  return reflection
end