13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
# File 'app/controllers/sortable_tree_controller.rb', line 13
def sortable_tree(class_name, options = {})
define_method("sort") do
resource_class = class_name.to_s.camelize.constantize
sorting_attribute = options.fetch(:sorting_attribute, 'pos')
parent_method = options.fetch(:parent_method, 'parent')
records = params[:cat].to_unsafe_h.inject({}) do |res, (resource, parent_resource)|
res[resource_class.find(resource)] = resource_class.find(parent_resource) rescue nil
res
end
errors = []
ActiveRecord::Base.transaction do
records.each_with_index do |(record, parent_record), position|
if sorting_attribute
record.send "#{sorting_attribute}=", position
end
if parent_method
record.send "#{parent_method}=", parent_record
end
errors << {record.id => record.errors} if !record.save
end
end
if errors.empty?
head 200
else
render json: errors, status: 422
end
end
end
|