简体   繁体   English

Ruby on Rails从ActionController插件模块中调用ActiveRecord模型

[英]Ruby on Rails calling ActiveRecord model from within ActionController plugin module

I've a got a method in ActiveRecord::User: 我在ActiveRecord :: User中有一个方法:

def create_user_from_json(user)
  @user=User.new(user)
  if @user.save!
    @user.activate!
  end
end

And I'm trying to call it in a plugin's module method. 我试图在插件的模块方法中调用它。 The plugin is json-rpc-1-1 . 插件是json-rpc-1-1 Here is the relevant code: 以下是相关代码:

class ServiceController < ApplicationController
  json_rpc_service :name => 'cme',                        # required
  :id => 'urn:uuid:28e54ac0-f1be-11df-889f-0002a5d5c51b', # required
  :logger => RAILS_DEFAULT_LOGGER                         # optional

  json_rpc_procedure :name => 'userRegister',
  :proc => lambda { |u| ActiveRecord::User.create_user_from_json(u) },
  :summary => 'Adds a user to the database',
  :params => [{:name => 'newUser', :type => 'object'}],
  :return => {:type => 'num'}
end

The problem is the code in the proc . 问题是proc的代码。 No matter whether I call ActiveRecord::User.create_user_from_json(u) or ::User.create_user_from_json(u) or User.create_user_from_json(u) I just get undefined method 'create_user_from_json' . 无论我叫ActiveRecord::User.create_user_from_json(u)还是::User.create_user_from_json(u)User.create_user_from_json(u)我都只会得到undefined method 'create_user_from_json'

What is the proper way to call a User method from the proc ? proc调用User方法的正确方法是什么?

I think this needs to be a class method instead of an instance method, declare it like this: 我认为这需要是一个类方法而不是实例方法,这样声明:

def self.create_user_from_json(user)
  ...
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM