acts_as_list helper
February 25th, 2008 • Uncategorized
# include this in application.rb
# or only in the controllers you need it.
# USAGE
# class FooParents::FoosController < ApplicationController
# include ActsAsListHelper
# protected
# def load_foo_parent
# @foo_parent = FooParent.find(params[:foo_parent_id])
# end
# public
# def create
# @foo = @foo_parent.foos.build(params[:foo])
# if @foo.save
# update_positions :foo_parent, :foo
# # ...
# else
# # ...
# end
# end
# def update
# @foo = @foo_parent.foos.find(params[:id])
# update_positions :foo_parent, :foo
# if @foo.save
# # ...
# else
# # ...
# end
# end
# #...
# end
module ActsAsListHelper
# support acts_as_list
def update_positions(parent_name, resource_name)
parent = instance_variable_get("@#{parent_name.to_s}")
resource = instance_variable_get("@#{resource_name.to_s}")
desired_position = params[resource_name.to_sym][:position].to_i
nr_of_nested_resources = parent.send(resource_name.to_s.pluralize).size
if desired_position > nr_of_nested_resources + 1 || desired_position < 1
# correct values that are out of list bounds
position = nr_of_nested_resources + 1
else
position = desired_position
end
# acts_as_list call
resource.insert_at(position)
end
end