【发布时间】:2020-09-17 11:18:20
【问题描述】:
假设:
class Item < ApplicationRecord
has_many :rowbills, dependent: :destroy
end
class Rowbill < ApplicationRecord
belongs_to :invoice, inverse_of: :rowbills
belongs_to :item
end
class Invoice < ApplicationRecord
belongs_to :customer
end
class Customer < ApplicationRecord
has_many :invoices
end
我想知道是否可以从 Items 开始检索 Rowbills、Invoices 和 Customers 上的某些字段?
我想我应该这样加入我的桌子吗?
Item.joins(rowbills: {invoice: customer})
或
Item.includes(rowbills: {invoice: customer})
这里是 schema.rb 的摘录(我只留下了我想恢复的字段)
create_table "items", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "label"
end
create_table "rowbills", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.decimal "total_price_vat_excluded_cache", precision: 8, scale: 2, default: "0.0"
t.integer "invoice_id"
t.integer "item_id"
t.index ["invoice_id"], name: "index_rowbills_on_invoice_id", using: :btree
t.index ["item_id"], name: "index_rowbills_on_item_id", using: :btree
end
create_table "invoices", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.integer "customer_id"
t.index ["customer_id"], name: "index_invoices_on_customer_id", using: :btree
end
create_table "customers", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "name"
end
我想浏览这些项目以在最后得到类似的东西:
items: [
{
label: "First Item",
customers: [
{
name: "First Customer",
total_price_vat_excluded_cache: "600.0",
},
{
name: "Second Customer",
total_price_vat_excluded_cache: "400.0",
}
]
},
{
label: "Second Item",
customers: [
{
name: "First Customer",
total_price_vat_excluded_cache: "200.0",
}
]
}
]
我希望我说清楚了,提前感谢那些可以帮助我的人。
【问题讨论】:
标签: mysql ruby-on-rails ruby