Skip to content

Instantly share code, notes, and snippets.

@Justinwceo
Created December 13, 2011 15:50
Show Gist options
  • Save Justinwceo/1472629 to your computer and use it in GitHub Desktop.
Save Justinwceo/1472629 to your computer and use it in GitHub Desktop.
Validations and Adding Products
<%= form_tag create_multiple_products_path, :method => :post do %>
<%= date_select("product", "purchase_date") %> # This acts as a global field for all Products.
<% @products.each_with_index do |product, index| %>
<%= fields_for "products[#{index}]", product do |up| %>
<%= render "fields", :f => up %>
<% end %>
<% end %>
<%= submit_tag "Done" %>
<% end %>
class ProductsController < ApplicationController
def new
@products = Array.new(2) { Product.new }
end
def create_multiple
Product.transaction do
begin # use to be create! but that was without any validations.
@products = current_user.products.create(params[:products].map { |_k, up| up.merge params[:product] })
redirect_to :back, :notice => "Success!"
rescue ActiveRecord::Rollback
redirect_to :back, :notice => "An error occurred, please try again."
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment