狂欢关系问题

Spree Relation Issue

我正在尝试向 Spree 商店添加产品附件功能。例如。 a product 有很多附件 documents:小册子、使用说明书等。我无法理解文档和产品之间的关系。

我可以使用回形针 gem 作为附件功能,因为 Spree 已经将它用于图像。

我有 "document" 型号:models/spree/document.rb:

class Spree::Document < ActiveRecord::Base
  belongs_to :products, class_name: "Spree::Product"
  has_attached_file :pdf
end

然后我尝试将文档模型关联到 models/spree/product_decorator.rb 中的 Spree::Product 模型:

Spree::Product.class_eval do
  has_many :documents, dependent: :destroy
end

然后我添加迁移:

class CreateDocuments < ActiveRecord::Migration
  def change
    create_table :spree_documents do |t|

      t.timestamps
    end
  end
end

class AddPdfToDocuments < ActiveRecord::Migration
  def self.up
    add_attachment :spree_documents, :pdf
  end

  def self.down
    remove_attachment :spree_documents, :pdf
  end
end

现在我进入 rails 控制台看看它是否有效:

#=> prod = Spree::Product.first
#=> prod.document
#=> PG::UndefinedColumn: ERROR:  column spree_documents.product_id does not exist
#=> LINE 1: ..."spree_documents".* FROM "spree_documents"  WHERE "spree_doc...
                                                             ^
#=> : SELECT "spree_documents".* FROM "spree_documents"  WHERE "spree_documents"."product_id" = 

好像我没有正确定义文档和产品之间的关系,但我不确定问题是什么。

您似乎从未在 Spree::Documents table 中添加 product_id 列。当您定义一个模型 belongs_to 另一个模型时,它会告诉 ActiveRecord 第一个将是其 table 中的 [relation]_id 列。

您只需要确保在迁移中添加 t.references :product,这样它看起来像:

class CreateDocuments < ActiveRecord::Migration
  def change
    create_table :spree_documents do |t|
      t.references :product
      t.timestamps
    end
  end
end