为form_tag呈现创建多个对象的错误消息?

时间:2011-12-15 07:08:52

标签: ruby-on-rails ruby ruby-on-rails-3

在此form_tag方案中使用时,我不确定如何显示表单的错误消息。我的代码允许我在表单上一次创建5个产品,但不幸的是只发出“发生错误......”的通知。

这是我的代码:

Product.rb

class Product < ActiveRecord::Base
  attr_accessible :price, :name, :purchase_date, :product_store, :in_category
  belongs_to :user
  belongs_to :store
  attr_reader :product_store
  validates_inclusion_of :in_category, :in => [true, false]
  validates_presence_of :name, :price, :store_id, :user_id
  validates_numericality_of :price

  def product_store=(id)
    self.store_id = id
  end
end

Products_controller.rb

class ProductsController < ApplicationController

  def new
    @products = Array.new(5) { Product.new }
  end

  def create_multiple
   @products = current_user.products.create(params[:products].map { |_k, p| p.merge params[:product] })
    if @products.each(&:save)
       redirect_to :back, :notice => "Success!"
    else
       redirect_to :back, :notice => "An error occured, please try again."
    end
  end
end

Form.html.erb

<%= form_tag create_multiple_products_path, :method => :post do %>
    <%= error_messages_for @product  %> 

       # the :purchase_date and :in_category are merged into all 5 Products.

            <%= date_select("product", "purchase_date")  %> 

            <%= label_tag :in_category, 'Add to Category?' %>
              <%= radio_button("product", :in_category, 1) %>
              <%= radio_button("product", :in_category, 0) %>

            <% @products.each_with_index do |product, index| %>
               <%= fields_for "products[#{index}]", product do |p| %>
                   <%= render "fields", :f => p %>
               <% end %>
            <% end %>

       <%= submit_tag "Done" %>
<% end %>

他们的2个问题。 1.获取fields_for以外字段的验证以显示.2。然后是fields_for内的那些。我怎么能这样做?

谢谢。

1 个答案:

答案 0 :(得分:7)

我一直在努力做同样的事情:

    <% @products.each_with_index do |product, index| %>
      <% product.errors.full_messages.each do |value| %>
        <li><%= value %></li>
      <% end %>

但是,这仅显示第一个产品出错的错误。您提交它,如果有后续产品有错误,您将被发送回该页面,下一个有错误的产品会显示其错误等。

编辑:知道了。这与我的验证方式有关。而不是:

if @products.all?(&:valid?)

这样做:

@products.each(&:valid?) # run the validations
if @products.all? { |t| t.errors.empty? }