All threads / Controller loop for has_many_through associations
Ask A Question


You’re not receiving notifications from this thread.

Controller loop for has_many_through associations

Siddharth Arun asked in Rails

I have the current models setup in my Rails app:

has_many :items, :through => :item_linkers
has_many :item_linkers, inverse_of: :recipe

belongs_to: recipe, inverse_of: :item_linkers
belongs_to: item, inverse_of: :item_linkers

has_many :recipes, through: :item_linkers
has_many :item_linkers, inverse_of: :item

In my show page I currently display all recipes that use a particular ingredient like this:

<% @item.item_linkers.each do |item_linker| %>
    <% %>
<% end %>

This is not the most elegant way imo and would like to do something like this in the controller:

@recipes =

Followed by this in the show page:

<% @recipes.each do |recipe| %>
    <% %>
<% end %>

But that doesn't seem to work. I get the following error. Any solutions on achieving this?

Cannot have a has_many :through association 'Item#recipes' which goes through 'Item#item_linkers' before the through association is defined.

Can you try changing the order of your has_many?

Like this:

has_many :item_linkers, inverse_of: :item
has_many :recipes, through: :item_linkers

Instead of:

has_many :items, :through => :item_linkers
has_many :item_linkers, inverse_of: :recipe


Let me know if that helps :)

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 70,078+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.