teorose
teorose

Reputation: 1

Rails one-way 'has_many' association

I am trying to make Rails-based application (and I'm just learning RoR as I go) and I stumbled upon this problem.

There are two models: Recipe and Item (food items). Recipe can have zero (we can create recipe before adding items) or many items. But a specific food item should not be bound to any recipe. That is why 'has_many' and 'belongs_to' won't work for me, as the latter does not fill this requirement.

If I was to do this without any framework, I would probably put an 'items' column in Recipe table, which would contain a list of item indices. But I have a hunch that this is not an appropriate way to do this in RoR since there are model associations in Rails. Please, could someone give me an idea how to go about this?

Upvotes: 0

Views: 330

Answers (1)

hashrocket
hashrocket

Reputation: 2222

I normally don't use has_and_belongs_to_many, but in your case it seems it might fit. You can use it like this:

class Recipe
  has_and_belongs_to_many :items
end

class Item
  has_and_belongs_to_many :recipes
end

You can also use has_many :through, but you would have to create a third table to join the Recipe and Item tables together.

class Recipe
  has_many :item_recipes
  has_many :items, through: :item_recipes
end

class ItemRecipes
  belongs_to :recipe
  belongs_to :item
end

class Item
  has_many :item_recipes
  has_many :recipes, through: :item_recipes
end

You can find more information here: Rails Associations

Upvotes: 2

Related Questions