简体   繁体   English

是否可以创建并传递模型对象的实例,但不能将其保存在Ruby on Rails中?

[英]Is it possible to create and pass an instance of a model object but not save it in Ruby on Rails?

I would like to be able to create a variable that holds an instance of a model object User but not save it to the database. 我希望能够创建一个包含模型对象User实例的变量,但不能将其保存到数据库中。 Is this possible? 这可能吗? Right now when I a do the following it saves it to the database: 现在,当我执行以下操作时,会将其保存到数据库中:

user = User.new
user.name = "John"
user.save

I would like to create a user variable that holds the previous information but not have to save it in the database. 我想创建一个保存先前信息的user变量,但不必将其保存在数据库中。 The reason is the function I need to use expects a User object and I don't want to save users yet at that point in the code. 原因是我需要使用的函数期望有一个User对象,而此时我还不想保存用户。

Thanks 谢谢

As Dave said, just don't save the user variable: 正如Dave所说的,只是不要保存用户变量:

user = User.new(:name => "John")

Now you can still use methods by passing in the user variable, even though it isn't saved to the database: 现在您仍然可以通过传递用户变量来使用方法,即使它没有保存到数据库中:

puts "The user's name is: #{user.name}"

您可以将其保存在会话中: session[:user] = user

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

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