Letting the users edit posts


Creating and deleting content is not enough. Let's give our users the possibility to modify it themselves. In this section we will implement the edit functionality.

Adding an Edit button

Go to app/views/posts/index.html.erb and below the <%= link_to("Delete", post_path(post), method: :delete) %> add the line:

<%=link_to("Edit", edit_post_path(post)) %>

Having changed the view, it's time to do this in the controller. Go to app/controllers/posts_controller.rb and add the lines:

def edit  
  @post = Post.find(params[:id])
end

What will the user see when they decide to edit the content? Let's make a view for that. Go to app/views/posts and create a new file called edit.html.erb. Type the following lines into the newly created edit.html.erb file:

<h1> Edit Post</h1>
<%= form_for @post do |form| %>
  <%= form.text_field :image_link %>
  <%= form.text_field :title %>
  <%= form.text_area :description %>
  <%= form.submit %>
<% end %>

Add the update action in your posts controller:

def update  
  @post = Post.find(params[:id])
  if @post.update_attributes(post_params)
    redirect_to posts_path
  else
    render :edit
  end
end

results matching ""

    No results matching ""