Tim*_*ley 1 ruby activerecord ruby-on-rails
我想Order对象由许多Product对象组成,所以我在object上建立了一个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
Run Code Online (Sandbox Code Playgroud)
连接表(又名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
Run Code Online (Sandbox Code Playgroud)