把你的錯誤放到你的app/views/layouts/application.html.erb中,高於yield並在你的nav下。
<% if flash[:notice] %>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:notice] %>
</div>
<% elsif flash[:error] %>
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:error] %>
</div>
<% elsif flash[:alert] %>
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:alert] %>
</div>
<% end %>
在模型中,驗證表單
validates :title, length: { minimum: 5 }, presence: true
應用程序/傭工內
/application_helper.rb
def form_group_tag(errors, &block)
if errors.any?
content_tag :div, capture(&block), class: 'form-group has-error'
else
content_tag :div, capture(&block), class: 'form-group'
end
end
表單內
<% if post.errors.any? %>
<div class="alert alert-danger">
<h4>There are <%= pluralize(post.errors.count, "error") %>.</h4>
<ul>
<% post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form_group_tag(post.errors[:title]) do %>
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
<% end %>
<%= form_group_tag(post.errors[:body]) do %>
<%= f.label :body %>
<%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter post body" %>
<% end %>
<div class="form-group">
<%= f.submit "Save", class: 'btn btn-success' %>
</div>
<% end %>
確保您有你的騙局中適當的邏輯troller too
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end