Rails 3.0.10, customer routes, post and form_for tag

孤街浪徒 提交于 2020-01-04 06:01:37

问题


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="&#x2713;" />
  <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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!