0

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

2
  • You should not write DB call in view file. You can create the object @articles = Article.all.sort.reverse.map { |a| [a.name, a.id] } and use that in the view file. Commented Jul 11, 2016 at 15:34
  • Good point, will do. Commented Jul 11, 2016 at 15:42

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

that's right, the route is for a single ressource. I'd assume you can omit the url.
Does @article need to be defined at all ahead of time? I'm trying this but it's still trying to route to /articles.
Its the same @article you're making the form_for.
Thanks @unused for pointing that out and being of so much use. ;)
So with the url omitted version, isn't that the same thing I started with? Any idea why I'm routing to the wrong place?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.