在之前的例子中,我们发现在new和edit两个view中,都使用到了form_with这个Rails内置的helper,我们可以把这部分内容提取出来,作为共通的部分供所有需要使用它的view使用。新建一个_form.html.erb的文件,将两个文件中的form_with装进来。
<%= form_with model: @article , local: true do |form| %>
<% if @article .errors.any? %>
< div id = "error_explanation" >
< h2 >
<%= pluralize( @article .errors.count, "error" ) %> prohibited
this article from being saved:
</ h2 >
< ul >
<% @article .errors.full_messages. each do |msg| %>
< li > <%= msg %> </ li >
<% end %>
</ ul >
</ div >
<% end %>
< p >
<%= form.label :title %> < br >
<%= form.text_field :title %>
</ p >
< p >
<%= form.label :text %> < br >
<%= form.text_area :text %>
</ p >
< p >
<%= form.submit %>
</ p >
<% end %>
|
然后我们把new.html.erb和edit.html.erb中的这个共通的部分用<%=
render
'form'
%>来代替。以后我们在实际项目开发的时候就可以这样操作了,简单明了,变更管理也非常方便,不易出错。