2010-07-09 30 views
2

我有一個名爲Action的模型。它看起來像這樣:在Rails中,當我在新模型中調用函數時出現NoMethodError

class Action < ActiveRecord::Base 
    def register_action(email,type) 
    @action = new() 
    @action.guid = "123456789" 
    @action.email = email 
    @action.action = type 

    action.guid if @action.save 
    end 
end 

如果我嘗試從我的user_controller訪問這個類,我得到一個錯誤。 我試圖使用的代碼是:

if (@User.save) 
    guid = Action.inspect() 
    guid = Action.register_action(@User.email,"REGISTER") 
    MemberMailer.deliver_confirmation(@User,guid) 
end 

Action.inspect()正常工作,所以我猜測,Action類可以看到,但它調用register_action行返回以下錯誤:

NoMethodError in UserController#createnew 
undefined method `register_action' for #<Class:0x9463a10> 
c:/Ruby187/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1994:in `method_missing' 
E:/Rails_apps/myapp/app/controllers/user_controller.rb:32:in `createnew' 

我在做什麼錯?

我是Rails的新手,所以很抱歉。

回答

6

問題是在這條線:

guid = Action.register_action(@User.email,"REGISTER") 

register_action是一個實例方法,而不是一個類的方法,所以你怎麼稱呼它在Action類,而不是Action類本身的實例

如果要定義register_action作爲一個類的方法,你應該這樣做是這樣的:

def self.register_action(email, type) 
    # ... Body ... 
end 
0

在你的register_action方法中,你需要做@action = Action.new而不是@action = new()。另外,您也可以構建這樣的:

@action = Action.new(:guid => "123456789", :email => email, :action => type) 

此外,您已經定義register_action爲您Action類的實例方法,但你調用它通過使用Action.register_action一個類的方法。它更改爲:

def self.register_action(email, type) 
    ... 
end 
2

變化

def register_action(email,type) 

要麼

def self.register_action(email,type) 

def Action.register_action(email,type) 
相關問題