Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Round 2:</p> <p>Ok, so I hope this will now help you. The way that you are implementing the dual address in one table isn't exactly the "rails" way. It always goes that if you want to do something you've got to do it like DHH. So rails has STI (<a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html" rel="nofollow noreferrer">Single Table Inheritance</a>) where you can have one super class with many classes inheriting from that.</p> <p>In your case, it shouldn't be too much work (I hope) to move this paradigm. </p> <p>Step 1: Cut a hole in a box</p> <p>Step 2: Update your migration files. You want the addresses table to have the key to it corresponding Customer. Then take out the billing_address_id and shipping_address_id columns in the Customer table because we don't need these anymore.</p> <p>You also want to add a field named <code>type</code> (if type is already taken there is a work around). Something like this:</p> <pre><code>create_table :addresses do |t| t.string :line1 t.string :line2 t.string :state t.integer :postcode t.integer :country_id t.integer :customer_id t.integer :type t.timestamps </code></pre> <p>Step 3: Update your models. Change your customer class to look like so: </p> <pre><code>class Customer &lt; ActiveRecord::Base has_one :postal_address has_one :billing_address accepts_nested_attributes_for :postal_address, :billing_address, :allow_destroy =&gt; true </code></pre> <p>Then you'll want to create two new files in the models directory: billing_address.rb and postal_address.rb. They should look like this:</p> <pre><code>class BillingAddress &lt; Address belongs_to :customer end class PostalAddress &lt; Address belongs_to :customer end </code></pre> <p>Step 4: Update Controllers. Now the only controller you showed in your question was customer_controller.rb but, fyi, this can apply for really anywhere. You want to replace <code>Address.new</code> with a call to instantiate either Shipping or Billing Addresses.</p> <pre><code>def new @customer = Customer.new @customer.postal_address = PostalAddress.new @customer.billing_address = BillingAddress.new respond_to do |format| format.html # new.html.erb format.xml { render :xml =&gt; @customer } end end </code></pre> <p>Hopefully this actually works and it makes up for my abysmal attempt earlier ;)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload