Rails foundationSort Order

Rails: CRUD Operations Part 2

In this episode we show you how to implement the edit, update, destroy and show actions in the controller.

Edit Action

# app/controllers/posts_controller.rbclass PostsController < ApplicationController  #...  def edit    @post = Post.where(id: params[:id]).first  end  #...end

You may be wondering where we will get the params[:id] from. It will be passed from the url. Which means when we generate the edit link it needs to have the :id somewhere in the path. For example posts/2/edit in this case the id is 2.

To generate the edit link in the view we'll need to edit our view.

# app/views/posts/_post.html.erb#...<p>  <%= link_to "Edit", edit_post_path(post) %></p>#...

The link_to will generate the path we need in order to pass the :id back to our controller.

Update Action

# app/controllers/posts_controller.rb#...def update  @post = Post.where(id: params[:id]).first  if @post.update_attributes(post_params)    redirect_to posts_path  else    # render the edit form again  endend#...

Let's try this out and see what happens!. One thing to note is it might be a good idea to order our index action with updated_at DESC so that the last updated post comes up first.

In the index action try this!

# app/controllers/posts_controller.rb#...def index  @posts = Post.order("updated_at DESC").allend

This should render the last updated post first in our index.

Destroy Action

# app/controllers/posts_controller.rbdef destroy  @post = Post.where(id: params[:id]).first  if @post.destroy    redirect_to posts_path  else      elseend

We need to render the link that will map to the destroy action.

# app/views/posts/_post.html.erb#...<p>  <%= link_to "Destroy", post_path(post), method: :delete %> </p>

Go ahead and try out the destroy action!

Next is the show page. The show page is generally used to display the detail of the object (in this case the post). Lets start off creating the post show page

# app/views/posts/show.html.erb<h1>  <%= @post.title %></h1><p>  <%= @post.body %></p>

That wraps it up for this episode!