Mateusz Urbański
Mateusz Urbański

Reputation: 7872

Rails: unable to destroy post

I'm building forum app based on Ruby on Rails. I have problem with destroy action in Post Controller. My Posts Controller:

class PostsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_topic, only: :create

  def new
    @post = @topic.posts.new
  end

  def create
    @post = @topic.posts.new(post_params)
    @post.user = current_user

    if @post.save
      flash[:notice] = 'Post created successfully!'
      redirect_to(:back)
    else
      render 'shared/_post_form'
    end
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    redirect_to(:back)
    flash[:error] = "Post was destroyed!"
  end

  private

  def set_topic
    @topic = Topic.find(params[:topic_id])
  end

  def post_params
    params.require(:post).permit(:content)
  end
end

This is my routes:

  resources :contact_forms, only: [:new, :create]
  match '/contact', to: 'contact_forms#new',    via: 'get'
  root 'static_pages#home'

  resources :forums, only: [:index, :show] do
    resources :topics, except: :index
  end

  resources :topics, except: :index do 
    resources :posts
  end

  devise_for :users
  resources :users, only: :show

I go to topic show action and i have link to delete post:

= link_to "Delete", topic_post_path(post.topic.forum.id, post.topic.id), method: :delete, data: {confirm: "You sure?"}, class: 'label alert

When i click it i have following error:

ActiveRecord::RecordNotFound in PostsController#destroy 
Couldn't find Post with id=46

Any ideas?

Upvotes: 1

Views: 2210

Answers (1)

Sergey K
Sergey K

Reputation: 5107

You are not passing post.id to destroy link. Try out:

= link_to "Delete", topic_post_path(post.topic.id, post.id), method: :delete, data: {confirm: "You sure?"}, class: 'label alert'

UPD: there is a shorter way to accomplish this:

= link_to "Delete", [post.topic.id, post.id], method: :delete, data: {confirm: "You sure?"}, class: 'label alert'

Upvotes: 2

Related Questions