当消息不符合验证要求但不知道如何实现时,我正在尝试在表单中闪烁消息。
我有以下设置:
模型/item.rb
class Item < ActiveRecord::Base
attr_accessible :condition, :day, :description, :subtitle, :title
validates :user_id, presence: true
validates :title, presence: true
validates :description, presence: true, length: { minimum: 20 }
belongs_to :user
end
控制器/items_controller.rb
class ItemsController < ApplicationController
before_filter :authenticate_user!
def new
@item = Item.new
end
def show
@item = Item.find(params[:id])
end
def create
@item = current_user.items.build(params[:item])
if @item.save
flash[:success] = "Your item has been saved"
redirect_to root_path
else
render 'new'
end
end
def destroy
@item.destroy
redirect_back_or root_path
end
end
最后是views/items/new.html.erb
<h1>Items Base</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@item) do |f| %>
<%= f.label :title, "Title" %>
<%= f.text_field :title %>
<%= f.label :subtitle, "Subtitle" %>
<%= f.text_field :subtitle %>
<%= f.label :condition, "Condition" %>
<%= f.number_field :condition %>
<%= f.label :description, "Description" %>
<%= f.text_field :description %>
<%= f.label :day, "Day" %>
<%= f.text_field :day %>
<%= f.submit "List", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
本质上,我希望能够显示“描述太短!”的消息。当用户将其留空或少于 20 个字符时,如果留空,则闪烁消息“需要标题”。关于如何最好地实现这一目标的任何想法。此外,如果有人有任何关于使用闪存的良好资源,将不胜感激。谢谢。