问题
I have this in my routes:
resources :events do
collection do
post 'moderate'
end
end
Rake routes tells me:
moderate_events POST /events/moderate(.:format) {:controller=>"events", :action=>"moderate"}
I have an "administration" controller that simply lists Events that need moderating:
@modevents = Event.where('moderated <> 1')
So far so good, all the events that haven't been moderated can be displayed in the view:
<%- @modevents.each do |me| -%>
Display Stuff here
<%- end -%>
I want to put a form in the loop that updated the moderated value but for the life of me I can't work out what to put in the form_for - I have tried:
<%= form_for me, :url => moderate_events_path do |f| %>
<%= f.submit %>
<% end %>
The html returned is:
<form accept-charset="UTF-8" action="/events/moderate" class="edit_event" id="edit_event_1" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="_method" type="hidden" value="put" />
When I click the "Submit" button I get the following error:
Couldn't find Event with ID=moderate
The solution is very simple, in routes change "post" to "put":
resources :events do
collection do
put 'moderate'
end
end
And now it works as it should. Updates, even custom ones are "put" functions.
回答1:
The answer is actually in the text above at the bottom but perhaps not obvious. If you are updating stuff you should be using "put" not post.
回答2:
You can also use POST by specifying:
<%= form_for me, :url => moderate_events_path, :method => :post do |f| %>
but as said before, the distinction needs to be made between updating and creating. The standard in rails is update==put, and create==post.
来源:https://stackoverflow.com/questions/8303752/rails-3-0-10-customer-routes-post-and-form-for-tag