9

My error message is "wrong number of arguments (0 for 1)"

for this line: @post = Post.destroy in my

PostsController#destroy

I have a model which is post.rb

My Posts Controller is here

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def index
    @posts = Post.all
  end

  def create
    @post = Post.new(post_params)

    if @post.save
      redirect_to @post
    else
      render 'new'
    end
  end

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

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

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

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

    if @post.update(params[:post].permit(:title, :text))
      redirect_to @post
    else
      render 'edit'
    end
  end

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

    redirect_to posts_path
  end

end

In my view I have this code:

<%= link_to 'Destroy', post_path(post),
  method: :delete, data: { confirm: 'Are you sure?' } %>

This is what it says I have for the parameters in the request

{"_method"=>"delete",
 "authenticity_token"=>"Pzsnxv8pt+34KIKpYqfZquDv3UpihkINGSJxomMNsW4=",
 "id"=>"3"}

What in the heck am I doing wrong??

camdixon
  • 852
  • 2
  • 18
  • 33

4 Answers4

13

You need to provide the ID to the destroy method:

Post.destroy(params[:id])

As stated here: http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-destroy

MurifoX
  • 14,991
  • 3
  • 36
  • 60
4

Precisely what the error says.

You can:

  • Call destroy on an instance with no argument, e.g., @post.destroy
  • On the class with an id, e.g., Post.destroy(an_id)
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
4

Here is your problem:

@post = Post.destroy

In Ruby you can destroy object in this way:

@post.destroy

Another tip: when you are using variables just inside model or controller, declare them as locals by not adding @ in front of them and use @ just for variables that you need to use globally. Learn more about that here: In what circumstances should I use instance variables instead of other variable types?

Community
  • 1
  • 1
2

I guess you wish to write:

@post.destroy
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69