views:

40

answers:

0

I have the following two models that have has_many and belongs_to relationships. I am trying to sort the ActionItems that belong to an ActionList using the reorder_action_items method.

class ActionItem < ActiveRecord::Base
  belongs_to :action_list

  default_scope order("sort_order asc, created_at asc")
end


class ActionList < ActiveRecord::Base
  has_many :action_items, :autosave => true

  scope :today, lambda {
    where("day = ?", Date.today)
  }

  scope :recent, lambda {
    where("day >= ? and day < ?", Date.today - 5.days, Date.today).includes(:action_items)
  }

  def reorder_action_items(new_order)
    new_order.each_with_index do |item, index|
       action_item = self.action_items.find(item)
       action_item.sort_order = index + 1
       action_item.save
    end
  end
end

Here is my controller action.

def update_order
  @idlist = params[:id]
  @todays_list = ActionList.today.first
  @todays_list.reorder_action_items(@idlist)
end

which gets called client side by jQuery.

This usually but not always works the first time reorder_action_items is called. When I try and sort a second time I always get the following error. What am I doing wrong?

NameError (undefined local variable or method `autosave_associated_records_for_action_list' for #<ActionItem:0xad22af8>):
/home/matthew/.rvm/gems/ruby-1.9.2-head/gems/activemodel-3.0.0.beta4/lib/active_model/attribute_methods.rb:358:in `method_missing'