2013-10-30 73 views
0

因此,舉例來說,從http://guides.rubyonrails.org/getting_started.html情況下,正如你所看到的,如果你嘗試創建無效後,你會看到錯誤消息:Rails的:一種觀點認爲,模型及其相關的模型

<%= form_for @post do |f| %> 
     <% if @post.errors.any? %> 
     <div id="errorExplanation"> 
     <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> 
     <ul> 
     <% @post.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
     <% end %> 
     </ul> 
     </div> 
     <% end %> 
     <p> 
     <%= f.label :title %><br> 
     <%= f.text_field :title %> 
     </p> 

     <p> 
     <%= f.label :text %><br> 
     <%= f.text_area :text %> 
     </p> 

     <p> 
     <%= f.submit %> 
     </p> 
    <% end %> 

如何實現爲關聯的評論模型渲染錯誤消息,請記住,評論創建表單位於posts/show視圖中?

回答

0

形態代碼通常保持匹配模型的文件夾中的在被在兩個new.html.erbedit.html.erb渲染的_form.html.erb部分(看一個很好的例子,產生用於示例模型的支架)。

你可以在你的情況下做什麼是渲染這個評論表單部分在帖子顯示操作。

app/views/posts/show.html.erb 
    <%= render 'comments/form', comment: @comment || @post.comments.build # Whatever you have here %> 

app/views/comments/_form.html.erb 
    <%= form_for comment do |f| %> 
    <%= render 'error_messages', target: comment %> 
    ... 
    <% end %> 

此外,示出的錯誤消息通常是所有形式的相同,因此,以除去複製,則可以提取此代碼到一個單獨的部分。

app/views/application/error_messages.html.slim # here is slim syntax, convert as nescessary 
/error explanation 
/
/= render 'shared/error_explanation', target: @school 
/
- if target.errors.any? 
    .error-messages 
    h4 Please correct the following fields: 
    ul 
     - target.errors.full_messages.each do |message| 
     li = message 

希望這會有所幫助。

+0

謝謝,用'渲染「文章/顯示」'在評論#中創建它現在解決了我的問題。 –

相關問題