简体   繁体   中英

How to assign the contents of one model to another in Rails?

I have the following create action:

def create
    @order = Order.new(params[:order])

    if params[:same_as_above] == "1"
      @order.billing_address.name = @order.shipping_address.name
      @order.billing_address.number = @order.shipping_address.number
      @order.billing_address.street = @order.shipping_address.town
    end

    if @order.save
      if @order.purchase
        render :action => "success"
      else
        render :action => "failure"
      end
    else
      render :action => 'new'
    end
  end

It works, but seems a bit cumbersome and brittle in the way i copy the shipping address to the billing address, attribute by attribute. Is there a better way please?

@order.billing_address.attributes = @order.shipping_address.attributes

绝招。

如果您的模型设置正确,则可以使用:

@order.billing_address = @order.shipping_address

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM