Rails Development Details (ii) CRUD

Source: Internet
Author: User

Create & Save

Create & Save

Order = order.new
order.name = "VIRUSSWB"
order.email = "asdf@exmaple.com"
order.save

You can save to the database after you call the Save method.

You can also use block to create and save.

Order.new do |order| 
  Order.name = "VIRUSSWB"
  order.email = "asdf@example.com"
  order.save 
End

You can also create and save using a hash.

Order = order.new ( 
  : Name => "virus" 
  : Email => "adf@example.com"
) 
Order.save

The default ID primary key is not assigned, and is the self-added column of integer.

The above method requires that the Save method be invoked to save to the database, and the Create method can be combined and created to be saved to the database at the same time.

Order = order.create ( 
  : Name => "virus" 
  : Email => "adf@exmaple.com"
)

You can also save multiple at once, as long as you pass an array to create.

Orders = 

Order.create ( 
  [{: Name => "Virus1", 
     : Email => "111@123.com"
   }, 
   {: Name => " Swb2 ", 
     : Email =>" 222@123.com "
   }] 
)

Return is also an array.

Create a model object directly from the form into the parameter.

@order = Order.new (Params[:order])

Order.find (1) can be used to get id=1 model, but if the datasheet does not exist id=1 model, it will throw Recordnotfound exception.

If you are using Order.where (: ID => 1). The one is to tell the database "I Need id=1 records", if there is no such record, it will not throw an exception and return the nil.

Reading Existing Rows

Read

An_order = Order.find (27)

Returns a record, and if not, throws a Recordnotfound exception.

Product_list = params[:p Roduct_ids]

Total = Product.find (product_list). SUM (&:p Rice)

To find incoming array, you can implement multiple records of the query, but if one of the IDs does not exist, still throw Recordnotfound exception.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.