我希望order对象由许多产品对象组成,所以我在对象上建立了habtm关系。
我想知道在habtm表中包含额外数据的方式是否“正确”(或者ruby/rails)。例如,如果我需要计算小计,并且可能需要重写行项目总计,那么我是将其存储为关联表的一部分,还是需要行项目对象或其他更好的对象?
谢谢

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

最佳答案

连接表(aka HABTM)纯粹用于连接关系,Rails(活动记录)忽略任何其他字段但是,您可以通过使用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

关于ruby-on-rails - 我应该在HABTM表中包括其他字段吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24140450/

10-13 02:17