Ruby on rails 为Rails 5中的关联创建联接表

Ruby on rails 为Rails 5中的关联创建联接表,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我有一个产品模型和一个变体模型,因为属于关联。有些变体完全属于一个产品,但也有其他变体可以属于多个产品。我可以在所属的关联上创建一个联接表吗,就像在有多个关联中一样 我的模型目前 product.rb class Product < ApplicationRecord has_many :variations, dependent: :destroy has_and_belongs_to_many :categories has_and_belongs_to_many :sub

我有一个
产品
模型和一个
变体
模型,因为
属于
关联。有些变体完全属于一个产品,但也有其他变体可以属于多个产品。我可以在
所属的
关联上创建一个联接表吗,就像在
有多个
关联中一样

我的模型目前

product.rb

class Product < ApplicationRecord
  has_many :variations, dependent: :destroy
  has_and_belongs_to_many :categories
  has_and_belongs_to_many :subcategories

  include FriendlyId
  friendly_id :name, use: :slugged

  def should_generate_new_friendly_id?
    name_changed?
  end
end
class Variation < ApplicationRecord
    has_and_belongs_to_many :categories
    has_and_belongs_to_many :subcategories
    belongs_to :product

    include FriendlyId
    friendly_id :name, use: :slugged

    def should_generate_new_friendly_id?
        name_changed?
    end
end
类产品
变体.rb

class Product < ApplicationRecord
  has_many :variations, dependent: :destroy
  has_and_belongs_to_many :categories
  has_and_belongs_to_many :subcategories

  include FriendlyId
  friendly_id :name, use: :slugged

  def should_generate_new_friendly_id?
    name_changed?
  end
end
class Variation < ApplicationRecord
    has_and_belongs_to_many :categories
    has_and_belongs_to_many :subcategories
    belongs_to :product

    include FriendlyId
    friendly_id :name, use: :slugged

    def should_generate_new_friendly_id?
        name_changed?
    end
end
class Variation
来自:

“属于”关联与另一个模型建立一对一的连接,这样声明模型的每个实例“属于”另一个模型的一个实例

当您在
变体
模型上执行
归属:产品
关联时,它希望有一个名为
产品id
的字段,该字段将指向关联的产品

使用示例:

variation = Variation.first
product = variation.product # this line will get the product which is associated to the variation by the product_id column.
因为它只能容纳一个整数(一个产品id),所以最好的选择是重新构造代码。使用“属于”是没有意义的,因为“有很多”关联

您需要将关联更改为多对多关联中的某个国王

要为您选择最佳选项,请阅读并了解

***确保更改关联时不会丢失数据:

这样做的想法:

  • 创建联接表
  • 复制变体表中的信息(variance.id和关联的产品id)
  • 开始使用新的关联

  • (您可能可以复制迁移文件中的数据,只需搜索如何执行即可)

    如果一些
    变体
    可以
    拥有许多产品,为什么不使用某种多对多关联呢?属于一个产品的
    变体
    在联接表上只有一条记录,而另一条则有多条记录records@ZivGalili确切地Studio Rooster过去一直在做这个
    关联
    问题,也许可以帮助他阅读有关活动记录、关联和Rails DB的详细指南building@FabrizioBertoglio如果你和齐夫在某处有一间私人房间,也许会有帮助。@ZivGalili谢谢你。我的问题是,这是一个活跃的项目,客户现在引入的变化不仅属于单一产品,而且可能属于许多产品;我没有重新构造关联的特权。@StudioRooster当您执行“属于:产品”关联时,变体模型希望有一个名为“产品id”的字段,该字段将指向关联的产品,并且由于它只能包含一个整数(一个产品id),因此最好的选择是重新构造。使用“属于”是没有意义的,因为“有很多”关联。只需分步进行,这样就不会丢失数据。首先创建联接表,然后从变体表(variance.id和关联的产品id)复制信息,然后开始将其用作多个关联。