我有一个方法(count_dupes
)以这种方式在控制台中正常运行:
@u = User.first
@c = @u.collections.first
[output of that find]
@c.count_dupes
[output]
@c.save!
[output followed by true]
基本设置如下:
has_many
个收藏品; has_many
项; has_many :dupe_items, class_name: 'Item', foreign_key:
'collection_dupe_id'
count_dupes
方法(来自集合模型):
def count_dupes
self.items.includes(:collection).each do |item|
threshold = item.holdback.presence || item.collection.holdback
if item.quantity > threshold
dupes_qty = item.quantity - threshold
item.collection_dupe_id = item.collection_id
item.dupe_quantity = dupes_qty
item.save!
end
end
end
当我在集合中的before_save方法中设置此集时,它会因堆栈级别太深而失败。删除.includes(:collection)
让它运行,但这需要永远在每个对象上,并有数千行像这样:
CACHE Collection Exists (0.2ms) SELECT 1 AS one FROM "collections" WHERE "collections"."name" = $1 AND ("collections"."id" != $2) AND "collections"."user_id" = 1 LIMIT $3 [["name", "Wahunsenekah (333B)"], ["id", 2], ["LIMIT", 1]]
在添加.includes(:collection)语句之后,仍然有数百个这样做,但是比以前少得多。
项目架构:
create_table "items", id: :serial, force: :cascade do |t|
t.string "name", limit: 255
t.string "location", limit: 255
t.text "description"
t.date "acquired_on"
t.decimal "price"
t.integer "issue_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "collection_id"
t.integer "quantity"
t.integer "holdback"
t.integer "collection_dupe_id"
t.integer "dupe_quantity", default: 0
t.index ["collection_id"], name: "index_items_on_collection_id"
t.index ["issue_id"], name: "index_items_on_issue_id"
end
我确信这是盯着我看的东西,我只是无法看到它,但是在我的空闲时间从不同的角度切割这几周,我不知所措。