Rails: Difference between create and new methods in ActiveRecord?

后端 未结 1 1653
耶瑟儿~
耶瑟儿~ 2020-12-13 06:01

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\")

         


        
相关标签:
1条回答
  • 2020-12-13 06:30

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

    0 讨论(0)
提交回复
热议问题