开发者

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

开发者 https://www.devze.com 2023-01-10 03:07 出处:网络
I have the following create action: def create @order = Order.new(params[:order]) if params[:same_as_above] == \"1\"

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

does the trick.


If your models are set up correctly, you can use:

@order.billing_address = @order.shipping_address
0

精彩评论

暂无评论...
验证码 换一张
取 消