Goalie
Goalie

Reputation: 3105

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. 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. 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.

Thanks

Upvotes: 0

Views: 213

Answers (2)

lee
lee

Reputation: 2439

As Dave said, just don't save the user variable:

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}"

Upvotes: 1

Samy Dindane
Samy Dindane

Reputation: 18706

You can save it in the session: session[:user] = user.

Upvotes: 0

Related Questions