0

this is a really simple question but I'm confused as to when I should use .new and .create in the controller. I guess what I am really asking is what are the uses for .new and what are the uses for .create? Thanks.

Dylan L.
  • 1,243
  • 2
  • 16
  • 35

1 Answers1

0

From the ActiveRecord::Base documentation:

create(attributes = nil) {|object| ...}

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

new(attributes = nil) {|self if block_given?| ...}

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). In both instances, valid attribute keys are determined by the column names of the associated table — hence you can‘t have attributes that aren‘t part of the table columns.

So create instantiates the new object, validates it, and then saves it to the database. And new only creates the local object but does not attempt to validate or save it to the DB.

From https://stackoverflow.com/a/2472416/634120

Community
  • 1
  • 1
martincarlin87
  • 10,848
  • 24
  • 98
  • 145
  • Thank you, but i'm confused as to when I would ever want to use just new? could you provide an example? – Dylan L. Dec 02 '14 at 16:40
  • if you don't want to save immediately, you could do `something = Something.new` then `if something.save...` or perhaps if you won't have some properties till later you could create it then set more properties, e.g. `something.property = variable` and then `save`. Just depends on what you're doing. `new` can come in handy but `create` is probably what is used more often. – martincarlin87 Dec 02 '14 at 16:44
  • perfect explanation. Thanks! – Dylan L. Dec 02 '14 at 16:47