Module: ActiveRecord::JsonHasMany

Defined in:
lib/active_record/json_has_many.rb,
lib/active_record/json_has_many/version.rb

Constant Summary collapse

VERSION =
"0.4.0"

Instance Method Summary collapse

Instance Method Details

#json_has_many(many, class_name: nil) ⇒ Object



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
# File 'lib/active_record/json_has_many.rb', line 7

def json_has_many(many, class_name: nil)
  one = many.to_s.singularize
  one_ids = :"#{one}_ids"
  one_ids_equals = :"#{one_ids}="
  class_name ||= one.classify
  many_equals = :"#{many}="
  many_eh = :"#{many}?"

  serialize one_ids, JSON

  include Module.new {
    define_method one_ids do
      super() || []
    end

    define_method many do
      class_name.constantize.where(id: send(one_ids))
    end

    define_method many_equals do |collection|
      send one_ids_equals, collection.map(&:id)
    end

    define_method many_eh do
      send(one_ids).any?
    end
  }
end