Using form to create data, this section will cover the content: Create form, redirect user, render views and flash messages.
1. Views Preliminary
Edit App/views/posts/index.html.erb This view file as follows:
<% @posts. Each do |post| %>
New_post is the new action's prefix, referring to [Ruby on Rails] and I learned the route map, but after it added the _path suffix.
Then edit the App/views/posts/new.html.erb view file as follows:
2. Binding to an ObjectThe question is, how to bind to the object?
The workaround is to first create an empty object and modify the new action as follows:
def new @post = post.new End
Then the view file is ready to use it, modify the App/views/posts/new.html.erb file as follows:
Use label to display the field name, because the context (content) is the text type, so it is better to display it with Text_area. Note the Form_for method.
3. The actual saveThe actual save is created by create, and the Create action is modified as follows,
Save success, then jump to the index page, otherwise stay on the new page, the specific code is as follows:
def create @post = Post.new (post_params) if @post. Save redirect_to Posts_path,:notice=> "Your post was Saved " else render" new " End End private def post_params Params.require (:p ost). Permit (: title,:context) End
which
1. Need for enhanced type support,
Post_params belong to strongly typed. It will guess what is in the parameters, what is allowed, and the nature of the interface is somewhat similar.
Are interested to know why the words look here.
2.notice belongs to a flash message, need to add support for Flash message, modify the global view file, that is app/views/layouts/application.html.erb as follows:
<! DOCTYPE html>
Some of the additions are:
<% Flash.each do |k,v| %> <p><%=v%></p><% end%>
Note <%= yield%>, which is equivalent to the Django block tag, defines a container area (placeholder), and other pages (index,new,edit,show) are rendered in this area.
Flash messages are displayed only once, for a request.
The final effect is as follows:
Reprint please specify this article from: http://www.cnblogs.com/Tommy-Yu/p/4141518.html, thank you!
[Ruby on Rails] and I learned to create data