尝试通过类别匹配产品和请求

问题描述 投票:0回答:1

我正在为uni制作rails marketplace app,用户可以根据他们的要求与特定产品进行匹配。

用户可以列出具有特定类别的产品。

用户还可以列出请求,他们可以在其中指定他们正在查找的产品及其类别。

目的是根据匹配的类别将请求与特定产品相匹配

这是我的模特

class Product < ApplicationRecord
  belongs_to :user
  has_many_attached :images, dependent: :destroy
  has_many :product_categories
  has_many :categories, through: :product_categories
  validates :user_id, presence: true
end

class Category < ApplicationRecord
  has_many :product_categories
  has_many :products, through: :product_categories
  validates :name, presence: true, length: { minimum: 3, maximum: 25}
  validates_uniqueness_of :name
end

class ProductCategory < ApplicationRecord
  belongs_to :product
  belongs_to :category
end

class Request < ApplicationRecord
  belongs_to :user
  has_many_attached :images, dependent: :destroy
  has_many :request_categories
  has_many :categories, through: :request_categories
  validates :user_id, presence: true
end

class RequestCategory < ApplicationRecord
  belongs_to :request
  belongs_to :category
end

我在考虑创建一个名为Match的新模型,将产品和类别集合在一起,还是在请求中更容易匹配?

ruby-on-rails ruby-on-rails-5
1个回答
0
投票

在我看来,你的新Match类基本上是has_many :through协会的连接表。假设您正在实现一个异步工作程序(例如Sidekiq / ActiveJob)来完成并进行“匹配”,您将需要将匹配连接到特定的Request,并且可能存储一些元数据(用户看到了Match)但他们拒绝了吗?)

所以,我可能会像这样生成一个Match类:

rails g model Match seen_at:datetime deleted_at:datetime request:references product:references

并建立关联如下:

class Match < ApplicationRecord
  belongs_to :request
  belongs_to :product
end

class Request < ApplicationRecord
  belongs_to :user
  has_many_attached :images, dependent: :destroy
  has_many :request_categories
  has_many :categories, through: :request_categories
  has_many :matches
  has_many :products, through: :matches
  validates :user_id, presence: true
end

class Product < ApplicationRecord
  belongs_to :user
  has_many_attached :images, dependent: :destroy
  has_many :product_categories
  has_many :categories, through: :product_categories
  has_many :matches
  has_many :requests, through: :matches
  validates :user_id, presence: true
end

此外,你可能想要将Request has_many:添加到你的Category模型中(我想你忘了那个):

class Category < ApplicationRecord
  has_many :product_categories
  has_many :products, through: :product_categories
  has_many :request_categories
  has_many :requests, through: :request_categories
  validates :name, presence: true, length: { minimum: 3, maximum: 25}
  validates_uniqueness_of :name
end

这项工作的重要部分是确定如何让您的应用定期查找匹配项 - 您可能需要从Active Job Basics文档开始。

© www.soinside.com 2019 - 2024. All rights reserved.