DEV Community

CalebMcCoy04
CalebMcCoy04

Posted on

all the CRUD

CRUD is a common acronym in the world of programming. It stands for Create, Read, Update, and Delete, and it refers to the four basic operations that can be performed on a database.

In this post, we'll take a look at how to implement CRUD using Ruby on Rails and JSON. Here's an example of a controller that performs CRUD operations on a Product model:

# Create a new record in the database
def create
  product = Product.new(product_params)

  if product.save
    render json: product, status: :created
  else
    render json: product.errors, status: :unprocessable_entity
  end
end

# Read a record from the database
def show
  product = Product.find(params[:id])

  render json: product
end

# Update an existing record in the database
def update
  product = Product.find(params[:id])

  if product.update(product_params)
    render json: product
  else
    render json: product.errors, status: :unprocessable_entity
  end
end

# Delete a record from the database
def destroy
  product = Product.find(params[:id])
  product.destroy

  head :no_content
end

private

# Strong parameters
def product_params
  params.require(:product).permit(:name, :price, :description)
end

Enter fullscreen mode Exit fullscreen mode

In this example, the controller methods return JSON data instead of rendering views. JSON (JavaScript Object Notation) is a lightweight data interchange format that is often used to exchange data between web applications and servers. In this case, the controller methods return a JSON representation of the Product object that is being created, retrieved, updated, or deleted. This allows a client application to access the data and use it however it needs to.

That's it! You can use this simple example as a starting point for implementing CRUD in your own Rails applications.

Top comments (0)