【问题标题】:Adding Order complicates Active Record Associations添加订单使 Active Record 关联复杂化
【发布时间】:2017-02-24 03:46:30
【问题描述】:

我有一个应用程序,客户可以在其中下订单以将物品发送到目的地。订单需要同时跟踪客户地址和目的地地址。

我从以下 Active Record 关联开始:

CUSTOMER
has_one :customer_address

CUSTOMER_ADDRESS
belongs_to :customer

DESTINATION
has_one :destination_address

DESTINATION_ADDRESS
belongs_to :destination

现在我想添加订单的概念。

所以我做了以下更改:

CUSTOMER
has_one :customer_address
has_many :orders

CUSTOMER_ADDRESS
belongs_to :customer

DESTINATION
has_one :destination_address

DESTINATION_ADDRESS
belongs_to :destination

ORDER
belongs_to :customer
has_one :customer_address, through: :customer
has_one :destination_address, through :destination

两个问题:

  1. 对于 ORDER 中的两个 has_one 关联,没有对称的 belongs_to。这似乎是错误的,但从概念上来说,belong_to ORDER 的客户或目的地也没有任何意义,部分原因是有很多订单,而客户或目的地只有一个地址。

  2. 什么是 ORDER 的正确迁移?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    迁移看起来像这样:

    class CreateOrder < ActiveRecord::Migration
      def change
        create_table :orders do |t|
          t.string :name
          # add price, products etc.
          t.integer :destination_id
          t.timestamps
        end
      end
    end
    

    您还需要一个连接表来将许多 customers 链接到许多 orders。像这样的:

    class CreateCustomerOrders < ActiveRecord::Migration
      def change
        create_table :customer_orders do |t|
          t.integer :customer_id
          t.integer :order_id
          t.timestamps
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2017-10-14
      • 2014-12-06
      • 2022-01-26
      相关资源
      最近更新 更多