Sunday, March 9, 2014

Update Blog with Favourites (Part 2)

Step 6: Adding Delete Favourite methods into Posts Controller

In app/controllers/posts_controller.rb,

class PostsController < ApplicationController
  before_filter :authenticate, :except => [ :index, :show ]

  # ... all the action go in here

  def add_favourite
    post = Post.find(params[:post_id])
    post.favourites.build(:post_id => params[:post_id])
    if post.save
      redirect_to post_path(post) #redirect_to action: :index
    end
  end

  def delete_favourite
    post = Post.find(params[:post_id])
    if post.favourites.size > 0
      post.favourites.first.destroy
      redirect_to post_path(post) #redirect_to action: :index
    else
      redirect_to post_path(post)
    end
  end

  # the authentication action
end

Step 7: Connecting URLs to Code by Editing Routes Config

In config/routes.rb,

QuickBlog::Application.routes.draw do
  resources :authors

  resources :comments

  get '/posts/add_favourite', to: 'posts#add_favourite'
  get '/posts/delete_favourite', to: 'posts#delete_favourite'
  resources :posts do
    resources :comments, :only => [:create, :destroy]
  end
end

Step 8: Edit the Views in Posts

In app/views/posts/show.html.erb,

  <p id="notice"><%= notice %></p>

  <%= render :partial => @post %>

  by <%= @post.author.name %>
  <br/>

  <%= link_to 'Edit', edit_post_path(@post) %> |
  <%= link_to 'Back', posts_path %>

  <p><%= link_to 'Add Favourite', "/posts/add_favourite?post_id=#{@post.id}" %> (<%= @post.favourites.size %>) | <%= link_to 'Delete Favourite', "/posts/delete_favourite?post_id=#{@post.id}" %></p>

Return to Internship Note (LoanStreet)
Previous Episode: Update Blog with Favourites (Part 1)
Next Episode: Update Blog with Tags

0 comments:

Post a Comment