【问题标题】:How to assign the contents of one model to another in Rails?如何在 Rails 中将一个模型的内容分配给另一个模型?
【发布时间】:2010-07-30 19:29:26
【问题描述】:

我有以下创建操作:

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

它有效,但在我将送货地址逐个属性复制到帐单地址的方式上似乎有点麻烦和脆弱。请问有更好的方法吗?

【问题讨论】:

    标签: ruby-on-rails model controller


    【解决方案1】:
    @order.billing_address.attributes = @order.shipping_address.attributes
    

    成功了。

    【讨论】:

      【解决方案2】:

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

      @order.billing_address = @order.shipping_address
      

      【讨论】:

      • ActiveRecord::AssociationTypeMismatch in OrdersController#create BillingAddress(#18825000) 预期,得到 ShippingAddress(#18874550)
      • 这基本上就是我所说的模型没有正确设置的意思......为什么Address 有两组类和表 - 为什么ShippingAddressBillingAddress 都有?跨度>
      • 因为一个表的数据会被保留,而另一个会定期清除。这就是我分离的原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多