Class: Bsm::Model::HasManySerialized::Builder

Inherits:
ActiveRecord::Associations::Builder::CollectionAssociation
  • Object
show all
Defined in:
lib/bsm/model/has_many_serialized.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build(model, name) ⇒ Object



13
14
15
16
# File 'lib/bsm/model/has_many_serialized.rb', line 13

def self.build(model, name, *)
  model.serialize "#{name.to_s.singularize}_ids", ::Bsm::Model::Coders::JsonColumn.new(Array)
  super
end

.define_accessors(model, reflection) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bsm/model/has_many_serialized.rb', line 18

def self.define_accessors(model, reflection)
  mixin = model.generated_association_methods
  name  = reflection.name
  klass = reflection.klass
  attribute_name = "#{name.to_s.singularize}_ids"

  mixin.redefine_method(name) do
    klass.where(klass.primary_key => send(attribute_name))
  end

  model.redefine_method("#{name}=") do |records|
    records = Array.wrap(records)
    records.each do |record|
      next if record.is_a?(klass)

      raise ActiveRecord::AssociationTypeMismatch, "#{klass.name} expected, got #{record.class}"
    end
    write_attribute attribute_name, records.map(&:id).sort
  end

  model.redefine_method("#{attribute_name}=") do |values|
    send "#{name}=", klass.where(klass.primary_key => Array.wrap(values)).select(:id).to_a.sort
  end
end

.macroObject



43
44
45
# File 'lib/bsm/model/has_many_serialized.rb', line 43

def self.macro
  :has_many
end

Instance Method Details

#valid_dependent_optionsObject



47
48
49
# File 'lib/bsm/model/has_many_serialized.rb', line 47

def valid_dependent_options
  []
end