Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails:我可以在模型的类方法中创建和保存对象实例吗?_Ruby On Rails_Class_Model_Instance - Fatal编程技术网

Ruby on rails Rails:我可以在模型的类方法中创建和保存对象实例吗?

Ruby on rails Rails:我可以在模型的类方法中创建和保存对象实例吗?,ruby-on-rails,class,model,instance,Ruby On Rails,Class,Model,Instance,在一个模型上使用类方法来创建同一个模型的新实例是可能的吗 场景是,我希望与外部API交互,在另一个服务上创建一个实例,然后在成功完成后将该新对象引用存储在本地模型中 例如,我想从控制器中调用如下内容: MyModel.interact_with_api_function([variables required]) 在模型上有这样一个类方法: def interact_with_api([variables required]) interacts with api, generates o

在一个模型上使用类方法来创建同一个模型的新实例是可能的吗

场景是,我希望与外部API交互,在另一个服务上创建一个实例,然后在成功完成后将该新对象引用存储在本地模型中

例如,我想从控制器中调用如下内容:

MyModel.interact_with_api_function([variables required])
在模型上有这样一个类方法:

def interact_with_api([variables required])
  interacts with api, generates object over there, returns result
  This.new(identifier: result, ...).save!
end

是否可以在模型上使用类方法来创建同一模型的新实例?

是的,你能做到。事实上,当您执行类似于MyModel.first的操作时,这正是发生的情况
first
是一个类方法,它从数据库中获取一行,创建模型的新实例,然后用从该数据库调用获取的数据填充它

场景是,我希望与外部API交互,在另一个服务上创建一个实例,然后在成功完成后将该新对象引用存储到本地模型中。

如果您认为对数据库的SQL调用类似于对外部API的调用(即,数据库是一个外部服务,就像您的API一样),那么
first
方法中的情况与您所做的并没有什么不同

类似地,
MyModel.create
方法是一种内置于Rails中的类方法,它创建该模型的新实例,然后将其保存到数据库中——同样,这与您正在做的事情没有什么不同

所以,我认为这很好