Forum: Ruby on Rails simple one-to-one relationship question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Harm de Laat (Guest)
on 2005-12-30 16:26
(Received via mailing list)
Hi all,

In my shop application I have created a form (rhtml file) containing
both
address and order information.

I created my fields: like the following:

For address info: <%= text_field 'address', 'postalcode'  %>
For order info: <%= text_field 'order', 'email'  %>

However when the following action gets submitted, my order object gets
saved
without any problems, but it never saves my Address object.
I would expect that the statement @order.save would also save my Address
object.

  def checkout_shipto
      if request.get?
          @order = Order.new
          @address = Address.new
          @order.address = @address
      else
          @order = Order.new(params[:order])
          @address = Address.new(params[:address])
          @order.address = @address
          if @order.save
              redirect_to(:action => "checkout_summary")
          else
              render_action('checkout_shipto')
          end
       end
  end

I have defined my model objects as follows:

class Order < ActiveRecord::Base
    has_many :line_items
    has_one :address, :dependent=>true
end

class Address < ActiveRecord::Base
    belongs_to :order
    validates_presence_of :street, :postalcode, :city, :country,
:address
end


Also, no validation on the Address object takes place. I think this is
because it never gets saved though....

Can you please help?

Regards,

Harm de Laat
Rick (Guest)
on 2006-01-02 20:13
Instead of using:

          @order.address = @address

try

          @order.address << @address

The << appends the new address record and sets the foreign keys
properly.
This topic is locked and can not be replied to.