I'm following a Rails 3.0 tutorial by lynda.com.
What's the difference between these two lines?
first_page = Page.new(:name => "First page") first_page = Page.create(:name => "First page")
By the way, this is great tutorial; I recommend it for any other newbies like me.
Basically the new method creates an object instance and the create method additionally tries to save it to the database if it is possible.
New instantiates a new Model instance, but it is not saved until the save method is called. Create does the same as new, but also saves it to the database. Sometimes you want to do stuff before saving something to the database, sometimes you just want to create and save it straight away.
new creates the object but doesn't save it. create! creates the object and tries to save it but raises an exception if validations fails, e.g. .
ActiveRecord::Persistence::ClassMethods#create create(attributes = nil, options = {}, &block)public Creates an object (or multiple objects) and saves it to the database, if validations pass.
Migrations are stored in files which are executed against any database that Active Record supports using rake. Here's a migration that creates a table: Rails keeps track of which files have been committed to the database and provides rollback features.
Basically the new method creates an object instance and the create method additionally tries to save it to the database if it is possible. create method 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.
To create Active Record models, subclass the ApplicationRecord class and you're good to go: This will create a Product model, mapped to a products table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model.
Basically the new
method creates an object instance and the create
method additionally tries to save it to the database if it is possible.
Check the ActiveRecord::Base documentation:
create method 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 method 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With