embell
embell

Reputation: 38

Rails 'select' form for Delete method of RESTful resource

This seems like it should be a simple thing, but I haven't been able to hunt down an illustrative example. Apologies if this question is redundant.

So I have a rails app, and I'm trying to work with a RESTful resource. This is what the route looks like:

config/routes.rb

resources :articles, only: [:index, :create, :destroy]

I want a simple form to delete these in case extras are added or whatever. So here are the form and controller I have so far:

app/views/articles/_delete.html.haml

%h1 Delete Article
- all_articles = Article.all.sort.reverse.map { |a| [a.name, a.id] }
= form_for @article, method: :delete do |f|
  .form-group
    = f.select :id, options_for_select(all_articles), class: 'form-control'
  = f.submit 'Delete', class: 'btn btn-danger'

When I submit this, I get 'No route matches [DELETE] "/articles"'. This is because the route for deletion is articles/:id :

DELETE    /articles/:id(.:format)    articles#destroy

So my goal is to get the submit button to grab the id, and send off to /articles/:id with the Delete method. If it helps, I'm on Rails 4.1.

I think the real pain point for me here though is not fully understanding how the form helper points to an action or passes data around. If anyone can elucidate I'd be appreciative.

I see that I can define a url on the form_for method, like so:

= form_for @article, method: :delete, url: articles_path do |f|

But how can I get the id from the form into that url?

Edit: Related: https://github.com/rails/rails/issues/1769

Upvotes: 0

Views: 687

Answers (1)

Kumar
Kumar

Reputation: 3126

Please try

= form_for @article, method: :delete, url: articles_path(@article) do |f|

And the url can be omitted. You may try like this

= form_for @article, method: :delete do |f|

Thanks to @unused

Upvotes: 2

Related Questions