我应该在HABTM表中包含其他字段吗?

时间:2014-06-10 11:59:22

标签: ruby-on-rails ruby activerecord

我希望Order对象由许多Product对象组成,因此我在对象上设置了HABTM关系。

我想知道它是否正确" (或Ruby / Rails)方式还包括HABTM表中的其他数据。例如,如果我需要计算小计并且可能需要覆盖行项目总计,我是否将其存储为关联表的一部分,或者我是否需要LineItem对象或更好的东西?

由于

ActiveRecord::Schema.define(version: 3) do

create_table "orders", force: true do |t|
    t.string   "order_id", null: false
    t.string   "order_status", default: "new"
    # <snip>
    t.decimal  "pay_total", precision: 8, scale: 2, null: false
end

add_index "orders", ["order_id"], name: "index_orders_on_order_id", unique: true, using: :btree
add_index "orders", ["order_status"], name: "index_orders_on_order_status", using: :btree

create_table "orders_products", id: false, force: true do |t|
    t.integer "order_id"  # migrated with belongs_to
    t.integer "product_id"  # migrated with belongs_to
    t.decimal "pay_cost",      precision: 8, scale: 2, null: false
    t.decimal "pay_discount",  precision: 8, scale: 2, default: 0.0
    t.decimal "pay_linetotal", precision: 8, scale: 2, null: false
end

add_index "orders_products", ["order_id", "product_id"], name: "index_orders_products_on_order_id_and_product_id", unique: true, using: :btree

create_table "products", force: true do |t|
    t.string  "name",  null: false
    t.decimal "price",  precision: 8, scale: 2,null: false
    t.boolean "active", default: true
end

1 个答案:

答案 0 :(得分:8)

连接表(又名HABTM)纯粹用于加入关系,Rails(Active Record)忽略任何其他字段。但是,您可以使用has_many through关系来解决这个问题,这样可以调用“LineItem”而不是“OrdersProducts”。

class Order
  has_many :line_items
  has_many :products, through: :line_items
end

class LineItem
  belongs_to :order
  belongs_to :product
end

class Product
  has_many :line_items
  has_many :orders, through: :line_items
end