Ecommerce shipping and billing address into one table in rails
ruby, ruby-on-rails, ruby-on-rails-3.1, ruby-on-rails-3.2
Solution
I'd suggest using a checkbox so the user can specify whether use the same billing and shipping address or type different ones.
In the form file you need to handle nested forms in the following way:
= form_for @order do f
= f.fields_for :billing_address do |ba|
= ba.text_field :address1
= ba.text_field:address2
= ba.text_field :city
= ba.text_field :state
= ba.text_field :zip
= ba.text_field :phone
= f.fields_for :shipping_address do |sa|
= sa.text_field :address1
= sa.text_field:address2
= sa.text_field :city
= sa.text_field :state
= sa.text_field :zip
= sa.text_field :phone
In your model don't forget to add:
accepts_nested_attributes_for :shipping_address
accepts_nested_attributes_for :billing_address
And probably need to add the autobuild to your address relations
belongs_to :billing_address, :class_name => "Address", autobuild: true
belongs_to :shipping_address, :class_name => "Address", autobuild: true
In the controller create/update actions, you just need to check the checkbox value and assign them equal, here's one approach:
@order.shipping_address = @order.billing_address if params[:checkbox_use_same_address] == true
Problem
I'm trying to create an address form with shipping and billing address on same page. When user gets ready for checkout , I want both shipping address form and billing address for to appear on same page. If billing address same as shipping address only record should be inserted into address table , if different two records has to be inserted and of course an update has to take place in orders table shipping_address_id,billing_address_id. Having only one address model, how do I achieve two forms with one submit button. Below is my model for address and orders I need some help in putting in controller also I'm trying to get a hash value for each billing and shipping Please help!!! ``` class Address < ActiveRecord::Base attr_accessible :name,:first_name,:last_name,:address1,:address2,:city,:state,:zip,:phone,:billing_default,: user_id,:billing_address, :shipping_address belongs_to :user has_many :billing_addresses, :class_name => "Order", :foreign_key => "billing_address_id" has_many :shipping_addresses, :class_name => "Order", :foreign_key => "shipping_address_id" class Order < ActiveRecord::Base attr_accessible :cart_id, :order_no, :sales_tax, :shipping_fee,:total,:order_state,:gateway_type,:transaction_id,:transaction_status,:ip_address,:card_verification,:card_number,:billing_address_id,:shippin g_address_id,:first_name,:last_name,:user_id,:card_expires_on,:authenticity_token belongs_to :cart belongs_to :user belongs_to :billing_address, :class_name => "Address" belongs_to :shipping_address, :class_name => "Address" attr_accessor :card_number has_many :transactions, :through => :order_id has_many :invoices has_many :order_details ```