Should I include other fields in a HABTM table?

让人想犯罪 __ 提交于 2019-12-08 04:48:47

问题


I would like an Order object to be comprised of many Product objects, so I set up a HABTM relationship on object.

I'm wondering if it's "correct" (or the Ruby/Rails) way to also include additional data within the HABTM table. For instance, if I need to compute the subtotal and there's a chance the line-item totals might need to be overridden, do I store that as part of the association table, or do I need a LineItem object or something better?

Thanks

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:


Join tables (aka HABTM) are purely for joining relationships and Rails (Active Record) ignores any additional fields. However, you can get around this by using a has_many through relationship, which would make sense to call "LineItem" instead of "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


来源:https://stackoverflow.com/questions/24140450/should-i-include-other-fields-in-a-habtm-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!