如何为特定验证闪烁错误

时间:2012-06-17 13:38:45

标签: ruby-on-rails-3

我尝试在不符合验证要求的情况下以表单形式刷新消息,但无法确定如何实现此目的。

我有以下设置:

模型/ 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个字符时,如果留空,则闪烁消息“标题必需”。有关如何最好地实现这一点的任何想法。此外,如果任何人有任何有关使用闪光灯的良好资源,将不胜感激。感谢。

1 个答案:

答案 0 :(得分:5)

我是这样做的:

以下是表格:

<%= form_for(@client) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <%= f.label :company_name %>
  <%= f.text_field :company_name %> 
  <%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
 <% end %>

这是我的error_messages偏:

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li>* <%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>