代码之家  ›  专栏  ›  技术社区  ›  seanyboy

在Rails中,我在新模型中调用函数时遇到了NoMethodError

  •  2
  • seanyboy  · 技术社区  · 14 年前

    我有一个模型叫做行动。看起来是这样的:

    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
    

    我尝试使用的代码是:

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

    Action.inspect()工作正常,因此我猜可以看到Action类,但是调用register\u 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新手,所以为自己的愚蠢道歉。

    3 回复  |  直到 14 年前
        1
  •  6
  •   mipadi    14 年前

    问题出在这条线上:

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

    register_action 实例 Action 班级,而不是 类本身。

    如果你想定义 注册\u操作

    def self.register_action(email, type)
      # ... Body ...
    end
    
        2
  •  2
  •   Salil    14 年前

    改变

    def register_action(email,type)
    

    或者

    def self.register_action(email,type)
    

    def Action.register_action(email,type)
    
        3
  •  0
  •   John Topley    14 年前

    在你的 register_action 你需要做的方法 @action = Action.new 而不是 @action = new()

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

    此外,您还定义了 Action 类,但您使用 Action.register_action . 更改为:

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