📅  最后修改于: 2023-12-03 14:47:08.752000             🧑  作者: Mango
Ruby on Rails is a web application framework written in the Ruby programming language. CRUD stands for Create, Read, Update, and Delete, which are the four basic functions of persistent storage.
In Rails, creating a new record in the database is done using the create
method. For example:
Post.create(title: 'My Title', content: 'Some content')
This creates a new post with the title "My Title" and content "Some content".
To retrieve records from the database, Rails provides many query methods such as find
, where
, order
, and more. Here's an example of retrieving all posts in descending order by created_at:
@posts = Post.order(created_at: :desc)
This retrieves all posts and assigns them to an instance variable @posts
that can be used in a view template.
To update an existing record, Rails provides the update
method. For example, to update the content of a post with a certain id:
@post = Post.find(params[:id])
@post.update(content: 'New content')
This finds the post with the given id and updates its content.
To delete a record from the database, Rails provides the destroy
method. For example, to delete a post with a certain id:
@post = Post.find(params[:id])
@post.destroy
This finds the post with the given id and deletes it from the database.
With Ruby on Rails, performing CRUD operations on a database is easy and intuitive. This is just a brief introduction to the topic, but there's much more to learn. By mastering Rails CRUD operations, you'll be able to build powerful web applications in no time.