Class: ForestLiana::BelongsToUpdater

Inherits:
Object
  • Object
show all
Defined in:
app/services/forest_liana/belongs_to_updater.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, association, params) ⇒ BelongsToUpdater

Returns a new instance of BelongsToUpdater.



5
6
7
8
9
10
11
# File 'app/services/forest_liana/belongs_to_updater.rb', line 5

def initialize(resource, association, params)
  @resource = resource
  @association = association
  @params = params
  @data = params['data']
  @errors = nil
end

Instance Attribute Details

#errorsObject

Returns the value of attribute errors.



3
4
5
# File 'app/services/forest_liana/belongs_to_updater.rb', line 3

def errors
  @errors
end

Instance Method Details

#performObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/services/forest_liana/belongs_to_updater.rb', line 13

def perform
  begin
    @record = @resource.find(@params[:id])
    if (SchemaUtils.polymorphic?(@association))
      if @data.nil?
        new_value = nil
      else
        association_klass = SchemaUtils.polymorphic_models(@association).select { |a| a.name.downcase == @data[:type] }.first
        new_value = association_klass.find(@data[:id]) if @data && @data[:id]
      end
    else
      new_value = @association.klass.find(@data[:id]) if @data && @data[:id]
    end
    @record.send("#{@association.name}=", new_value)

    @record.save
  rescue ActiveRecord::SerializationTypeMismatch => exception
    @errors = [{ detail: exception.message }]
  rescue => exception
    @errors = [{ detail: exception.message }]
  end
end