Home > Software design >  how to connect two table that has no relation in rails
how to connect two table that has no relation in rails

Time:05-11

I have a table called foods and categories, but this table has no relation, I want to connect them through another table called food_category. And I want to make one-to-one relation between food and category maybe the diagram looks like this

enter image description here

class Food < ApplicationRecord 
  has_one :category
end

class Category < ApplicationRecord
  has_one :food
end

class FoodCategory < ApplicationRecord
  belongs_to :category
  belongs_to :food
end

Is it possible to do this?

CodePudding user response:

Yes, this is possible. You just need to do

has_one :category, through: :food_categories

as discussed in the Rails docs here.

However, this is a long-winded way to go about this kind of association. If it's going to be one-to-one, why not just add a foreign key to Category from Food? And presumably, you would actually want Category to contain many Food records? Seems like the below would make more sense:

class Food < ApplicationRecord 
  belongs_to :category
end

class Category < ApplicationRecord
  has_many :food
end

CodePudding user response:

class Food < ApplicationRecord 
  has_one :food_category
  has_one :category, through: :food_categories
end

In rails console, you can access like this

Food.find(:id).categories
  • Related