Reputation: 3289
I have a products
model and a variations
model as a belongs_to
association. There are some variations that absolutely belong to a single product, but there are others that can belong to many products. Can I create a join table on a belongs_to
association like in a has_and_blongs_to_many
association?
My Models Currently
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
variation.rb
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
Upvotes: 0
Views: 1500
Reputation: 1445
From Rails guides association basics - the belongs_to association:
A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.
When you do the belong_to :product
association on the Variation
model, it expect to have a field named product_id
which will point to the associated product.
use example:
variation = Variation.first
product = variation.product # this line will get the product which is associated to the variation by the product_id column.
Since it can hold only one integer (one product id) the best option is to restructure your code. It makes no sense to use a "belong_to" as "has_many" association.
You need to change the association to some king of many to many association.
To chose the best option for you, read and learn the differences in the Rails guides - Association Basics
*** Make sure you won't lose your data when changing the association:
Idea of doing that:
(You can probably copy the data in the migration file, just search how to do it)
Upvotes: 1