Skip to content

Instantly share code, notes, and snippets.

@lksv
Created January 10, 2014 14:59
Show Gist options
  • Save lksv/8355777 to your computer and use it in GitHub Desktop.
Save lksv/8355777 to your computer and use it in GitHub Desktop.
def update_tree(options = {}, &block)
authorize!(action_name.to_sym, resource_class)
parent_id = params[:parent_id]
# check that parent shoud by node which is visible for the user.
authorize!(:list, params[:parent_id])
err_exit = proc { |r|
render json: {
success: false,
msg: t('basepack.tree_list.update_tree.error', name: resource.to_label,
msg: resource.errors.full_messages.join(',')).to_json
}
return #it is Proc, note we are exiting form the whole method.
end
resource_class.transaction do
# parent id can be changed using every d & d method
resource.parent_id = parent_id
# if +position+ attribute exists, it is orderable tree
# and position of the tree has to be set
if resource.respond_to?(:position)
method = params[:method]
ancestry = resource2.ancestry
if method == "over" # new node in subtree, set position to last
pos = resource.siblings.order('position').last.position + 1
resource.position = pos
err_exit(resource) unless resource.save
end
# move before/after resource2
# if moving before, position of resource2 has to be updated too
position_cond = resource2.position
position_cond += 1 if method == "after"
nodes = resource2.siblings.where('position >= ?', position_cond)
nodes.each do |n|
authorize!(:update, n)
position_cond += 1
n.position = position_cond
err_exit(n) unless n.save
end
resource.position = position_cond
err_exit(resource) unless resource.save
end # end transaction
render json: { success: true }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment