如果我使用 Rails 4 进行测试:
rails g scaffold post title description:text
会生成表单源:
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
还有 scaffold.css.scsss:
body {
background-color: #fff;
color: #333;
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a {
color: #000;
&:visited {
color: #666;
}
&:hover {
color: #fff;
background-color: #000;
}
}
div {
&.field, &.actions {
margin-bottom: 10px;
}
}
#notice {
color: green;
}
.field_with_errors {
padding: 2px;
background-color: red;
display: table;
}
#error_explanation {
width: 450px;
border: 2px solid red;
padding: 7px;
padding-bottom: 0;
margin-bottom: 20px;
background-color: #f0f0f0;
h2 {
text-align: left;
font-weight: bold;
padding: 5px 5px 5px 15px;
font-size: 12px;
margin: -7px;
margin-bottom: 0px;
background-color: #c00;
color: #fff;
}
ul li {
font-size: 12px;
list-style: square;
}
}
结果是:
但是如果我想使用twitter bootstrap的form error class,比如:
如何用正确的方式去做?有好的 gem 导出吗?
事实上,我想要这种风格:
最佳答案
您可以使用 rails-bootstrap-forms
gem,我们可以通过将自定义 Bootstrap 样式应用于我们的表单来自定义 Rails 表单。
gem 文件:
gem 'bootstrap_form'
应用程序.css.scss:
*= require rails_bootstrap_forms
表格
<%= bootstrap_form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
请引用这些链接以获得进一步的帮助:
https://github.com/bootstrap-ruby/rails-bootstrap-forms
Styling form error message - bootstrap/rails
希望对您有所帮助。
形式应该是:
<%= bootstrap_form_for(@question) do |f| %>
<%= f.alert_message "Please input values." %>
<%= f.text_field :title %>
<%= f.text_field :description %>
<%= f.submit %>
<% end %>
关于css - 如何通过 rails 框架使用 twitter bootstrap 显示漂亮的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053218/