【发布时间】:2015-09-04 18:12:01
【问题描述】:
我正在使用 Mongoid v4.0.2,我在使用 .includes() 时遇到了一个有趣的问题。我有一张代表发票的记录,上面有收费清单。
我想查询单个发票并在运行查询后填充费用。 According to the docs(搜索“Eager Loading”),我应该能够做这样的事情来让 Mongoid 填充费用:
Invoice.includes(:charges).find_by({ _id: <objectId> })
当我取回记录时,费用仍然显示为 ObjectId 的列表,并且删除 .includes() 似乎没有任何效果。我已验证我正在查询的记录中存在每项费用,所以我很困惑为什么它们没有填充。
我相信我已经正确设置了数据模型,但为了完整起见,我会将它们包含在此处。
class Invoice
include Mongoid::Document
has_many :charges
field :status, type: String
field :created, type: Time, default: -> { Time.now }
end
class Charge
include Mongoid::Document
field :created, type: Time, default: -> { Time.now }
field :transactionId, type: String
field :category, type: String
field :amount, type: Float
field :notes, type: String
belongs_to :invoices
end
【问题讨论】:
-
应该是
belongs_to :invoice(单数),但这可能只是您问题中的一个错字...... -
不,这不是错字。但是,在更改
belongs_to:值后它仍然没有填充。 -
在更改 belongs_to 语句后,您是否更新了您的费用集合中的文件?
-
@MarcoSandrini 我正在另一个应用程序中创建这些记录,所以我更想匹配数据库中已经创建的内容。
-
你在哪里存储“foreign_key”?作为负责人的
invoice_id或作为发票模型中的一组ID。 Mongoid 在将关系标记为 Referenced 1-N 时期望前者