Search code examples
ruby-on-railsroutesassociationsbutton-to

RoR how to get button_to path to /needs/4 instead of /needs.4?


I am still fairly new to RoR and I am trying to delete an object with a button_to delete button. With the code I wrote though, it gets me to /needs.4 instead of /needs/4 when I try to get it to /needs/:id for the destroy method. A "need" is created via the needs-controller and a needs new.html.erb page, and then shows up in the user's show page. from there, a user is supposed to be able to delete his/her need. This is the error I get:

ActiveRecord::RecordNotFound in NeedsController#destroy

Couldn't find Need with id=@userneed
Rails.root: /Users/mcn/Dropbox/Code/GA/Projects/GA_projects/p4_final/flatcircle

Application Trace | Framework Trace | Full Trace
app/controllers/needs_controller.rb:20:in `destroy'
Request

Parameters:

{"_method"=>"delete",
 "authenticity_token"=>"Fv6EcMNJQEjtw1naQVMw77lkCGjTJR7ui2FD53aoZfc=",
 "id"=>"@userneed"}

And this is my code:

Needs_controller:

def destroy
    Need.find(params[:id]).destroy
    redirect_to :controller => :users, :action => :show, :id => current_user.id, :flash => { :success => "Your search post was deleted." }
  end

User's show page button_to line:

  <%= button_to "delete", '/needs/@userneed', method: :delete, data: { confirm: "You sure?"} %>

and on same page:

@userneed = @current_user.needs.last

Routes.rb

delete "/needs/:id", to: "needs#destroy"
get "/needs/:id", to: "needs#show"

Super confused, let me know if you know how to solve it!


Solution

  • try <%= button_to "delete", '/needs/<%= @userneed %>', method: :delete, data: { confirm: "You sure?"} %>

    and @userneed = @current_user.needs.last.id

    But I think its best to use a link instead a button...something like <a href="<%=model_path(@model) %>" data-method="delete" data-confirm="are you sure?">delete</a>