Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: wrong number of arguments (0 for 1) for .destroy

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??

like image 628
camdixon Avatar asked Jan 29 '14 18:01

camdixon


2 Answers

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

like image 169
MurifoX Avatar answered Sep 19 '22 18:09

MurifoX


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?

like image 28
ObiVanKaPudji Avatar answered Sep 18 '22 18:09

ObiVanKaPudji