Created
December 13, 2011 15:50
-
-
Save Justinwceo/1472629 to your computer and use it in GitHub Desktop.
Validations and Adding Products
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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