2
我不知道如何在此form_tag
方案中使用它時顯示我的表單的錯誤消息。我的下面的代碼允許我一次在表單上創建5個產品,但不幸的是只會呈現「發生錯誤...」的通知。爲form_tag創建多個對象的渲染錯誤消息?
這裏是我的代碼:
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.map(:有效嗎?)所有`有點清潔。?不像`@ products.all?(&:valid?)`,它會驗證所有產品,然後檢查它們是否全部有效。 `@ products.all?(&:valid?)`的問題是,它會一直運行到第一個無效記錄。 – 2011-12-24 19:29:31