Rails 3: How to submit form inside another model's show method
I have a page in pages#show. I created a messages form inside that page. When submitted I get this error "Routing Error No route matches [POST] /pages/9".
So it's a form inside another's model show page. In this case it's a form that will work with the Message model, inside a Page show view.
<%= form_for(@message, :url => page_path(@page)) do开发者_开发技巧 |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
You may use AJAX to send the request to the '/messages' path, then receive and display the errors without reloading the page, OR change your routes a little.
Define an additional route:
match "pages/:id", :via=>:post, :controller=>"pages", :action=>"create_message"
Then define the action create_message
in similar way to usual create
actions: if the message has been created, redirect to /pages/:id
, and if there was an error, render the "show" action.
In case of error, you should also remember about returning proper HTTP status code when rendering the "show" view (code 422 looks like a good one), and just make the "show" view aware of possible @message
error messages.
I am not sure whether I like this way of creating messages (a POST /page/3/messages
looks like a better solution), but I am also not confident that this is a bad thing. ;-)
The url specified:
url => page_path(@page)
Should be the route that is used to create messages.
You can run rake routes
to find all the routes your app currently has.
You're giving it :url => page_path(@page)
, which I assume gives you /pages/9
. Try just omitting the :url. It should guess that this is a new message and take you to the right path. Otherwise, if you want to be explicit, it should be something like :url => message_path
(note no argument to message_path
since a POST to a resource's root path is normally mapped to the create action).
This is not exactly what I wanted, but it'll do for now: http://matharvard.ca/posts/2011/aug/22/contact-form-in-rails-3/
精彩评论