hellomello
hellomello

Reputation: 8597

rails delete a record with multiple conditions

I'm trying to use .find or .where to find a certain record in my database to delete, but I'm having trouble...

I have this in my routes

resources :objects do
  delete 'item' => 'objects#item_destroy', :as => :item_destroy
end

In my controller

def item_destroy
  @object = Object.find(params[:object_id])
  @puser = Puser.find_by_user_id(current_user)
  if @mine = Mine.where(:puser_id => @puser).where(:object_id => @object)
    @mine.destroy
    respond_to do |format| 
      format.html { redirect_to :back } 
      format.xml { head :ok } 
    end
  end
end

However I'm getting this error:

wrong number of arguments (0 for 1)

My link to destroy is this:

<%= link_to "Delete me", object_item_destroy_path, method: :delete, :class => "pure-button pure-button-primary" %>

Can someone assist me?

Thanks!

EDIT::

also, when I'm only getting these parameters:

{"_method"=>"delete",
 "authenticity_token"=>"fdsagfHFUWlfiwoqobGBW92&9",
 "object_id"=>"21"}

I'm not getting puser_id?

Upvotes: 1

Views: 1629

Answers (2)

Surya
Surya

Reputation: 16022

Try this:

<%= link_to "Delete me", object_item_destroy_path(object_id: @object), method: :delete, :class => "pure-button pure-button-primary" %>

UPDATE:

Change you objects_controller.rb file's method:

def item_destroy
  @object = Object.find(params[:object_id])
  @puser = Puser.find_by_user_id(current_user)
  if @mine = Mine.where(:puser_id => @puser).where(:object_id => @object).first
    @mine.destroy
    respond_to do |format| 
      format.html { redirect_to :back } 
      format.xml { head :ok } 
    end
  end
end

Here, when you say: Mine.where(:puser_id => @puser).where(:object_id => @object), it will give you an ActiveRecord::Relation object, not the Mine's object, and hence destroy method is not available the way you're trying to invoke it.

I also encourage you to use associations here. Like:

@puser.mines.where(:object_id => @object).first
# or
@puser.mines.find_by_object_id(@object)

Upvotes: 1

Sherwyn Goh
Sherwyn Goh

Reputation: 1352

 <%= link_to "Delete me", object_item_destroy_path**(:id => "something" or the object you want to delete)**, method: :delete, :class => "pure-button pure-button-primary" %>

Yup, no id is being passed in because no id is being put into the link.

Upvotes: 0

Related Questions