Search code examples
rubyruby-on-rails-5ruby-on-rails-6

Delete post from another controller?


I have two controllers in my app. as of now- User & Post.The user controller has only these methods as of now are - index,new,create and show. I show users posts in users#show view page only.

I wanted to add a functionality to delete the post. I added the method to delete post in post's controller....But i when click on delete button it shows an error The action 'destroy' could not be found for UsersController

Which is true, I dont have method destroy in users controller.

How can i delete post using posts controller only? I dont want to user controller here , to delete post as - i want to add functionality to delete user in future

class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(set_params)
    if @user.save
      UserNotifierMailer.send_signup_email(@user).deliver
      flash[:success] ="Success"
      redirect_to new_sessions_path and return
    else
      render 'new'
    end

  end

  def show
    @user = User.find(params[:id])
    @posts = @user.posts
  end

  private

  def set_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end

  def post_params
    params(:post.require).permit(:title, :body)
  end

end

User#show

<div class="col-md-8">
    <h1> Posts ( <%= @posts.count %> ) </h1>
    <%= @posts.each do |p| %>

        <div class="form-field">
            <h4><b><%= p.title %></b>  <%= link_to "Edit", edit_post_path(p.id), class: "btn 
                 btn-warning col-md-2-offset", style: "align-right" %><%= link_to "Delete", 
                 @post , method: :delete,data: { confirm: "You sure? "}, class: "btn btn-danger 
                 col-md-2-offset", style: "align-right" %></h4> 
            <%= p.body %>
        </div>
    <% end %>

Post Controller - delete method

 def destroy
     @post = Post.find(params[:id])
     @post.destroy
     flash.now[:success] = "Succesfully Deleted"
     redirect_to user_path(current_user)
  end

Routes

Rails.application.routes.draw do
  root 'posts#index'
  resources :users
  resources :posts
  resource :sessions, only: [:new, :create, :destroy]
  resources :passwords, only: [:new, :create, :edit, :update]
end

Rake routes : DELETE /posts/:id(.:format) posts#destroy


Solution

  • I think you mean p and not @post:

    <%= link_to "Delete", p, ... %>
    

    In your view @post is most likely nil, which is confusing to link_to, and hence the error.