2010-07-06 91 views
1

我有以下模型,但无法使自定义方法reorder_action_items正常工作。我显然缺少一些基本的东西。Rails 3添加ActiveRecord模型方法

class ActionList < ActiveRecord::Base 
    has_many :action_items 

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

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

class ActionItem < ActiveRecord::Base 
    belongs_to :action_list 
end 

这是来自我的控制器的动作。

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

这里是错误的日志输出。

Started POST "/welcome/update_order" for xxx.xxx.xxx.xx at 2010-07-06 13:50:46 -0500 
    Processing by WelcomeController#update_order as */* 
    Parameters: {"id"=>["3", "1", "2"]} 
    SQL (0.2ms) SELECT name 
FROM sqlite_master 
WHERE type = 'table' AND NOT name = 'sqlite_sequence' 
Completed in 14ms 

NoMethodError (undefined method `action_items' for #<Class:0xa062cb4>): 
/home/matthew/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.0.beta4/lib/active_record/base.rb:1041:in `method_missing' 
+0

你究竟想要做什么以及你得到了什么样的错误(如果有的话)? – 2010-07-06 18:40:06

+0

发生了什么?当你调用ActionList.reorder_action_items(order)它会引发一个缺少错误的方法? – robertokl 2010-07-06 18:41:11

+0

'ActionList.today'返回什么? – 2010-07-06 19:45:58

回答

4

你试图访问一个实例方法作为方法。

def self.reorder_action_items(new_order) 
    new_order.each_with_index do |item, index| 
     # here, self is not an instance of ActionList 
     # and action_items is an instance method 
     ai = self.action_items.find(item) 
     ai.sort_order = index 
     ai.save 
    end 
end 
+0

谢谢,这使我能够解决我的问题。 – MHinton 2010-07-06 21:20:11

+0

不客气! – 2010-07-07 11:54:58

相关问题