Lea*_*RoR 2 ruby ruby-on-rails 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.我怎么能这样做?
谢谢.
我一直试图做同样的事情,用这个:
    <% @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? }