【问题标题】:Associating custom model with Spree将自定义模型与 Spree 关联
【发布时间】:2014-11-25 11:55:03
【问题描述】:

我想添加Service 类别,和Spree::Product 一样,为此我必须定义一些关联,如下所示

class Service < ActiveRecord::Base
      has_many :images, -> { order(:position) }, as: :viewable, class_name: "Spree::Image", dependent: :destroy

      has_many :taxons, class_name: "Spree::Taxon", dependent: :destroy

      validates :name, presence: true,
                  length: { minimum: 5 }

end

现在,首先,这是定义此类类别的正确方法还是我应该使用其他约定来定义Service,对于:taxons 关联,我是否应该定义迁移以在spree_taxons 中添加service_id 列桌子?

【问题讨论】:

    标签: ruby-on-rails spree


    【解决方案1】:

    这里有一个设计问题,Spree使用一个模型来连接TaxonsProducts,你应该创建它并命名为services_taxon ,迁移应该是这样的:

    class CreateServiceTaxon < ActiveRecord::Migration
      def change
        create_table :service_taxon do |t|
          t.integer :service_id
          t.integer :taxon_id
        end
      end
    end
    

    在服务模型上你应该添加:

    class ServiceTaxon < ActiveRecord::Base
      belongs_to :service, :class_name => 'Service', :foreign_key => 'service_id'
      belongs_to :taxon, :class_name => 'Spree::Taxon', :foreign_key => 'taxon_id'
    end
    

    我应该指出的另一件事是,如果您需要一些已经由 spree 团队在产品模型上创建的功能,您应该真正考虑使用他们的,或者至少尝试扩展产品模型。

    【讨论】:

      【解决方案2】:

      您需要一个新的连接模型,例如 ServiceTaxons,而不是添加一个 service_idSpree::Taxon。如果您查看 Products 是如何链接到 Taxons 的,那是通过 spree_product_taxons 表。

      更重要的部分是你是否需要一个新的Service 类。你最好把你的服务当作产品。产品在 Spree 系统中根深蒂固,您正在为自己创造大量工作来尝试实现与它并存的另一个模型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 1970-01-01
        • 2018-10-02
        • 1970-01-01
        相关资源
        最近更新 更多