Skip to main content

Controller loop for has_many_through associations

Rails • Asked by Siddharth Arun

I have the current models setup in my Rails app:

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

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

Item
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| %>
    <% item_linker.recipe.name %>
<% end %>

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

@recipes = @item.recipes

Followed by this in the show page:

<% @recipes.each do |recipe| %>
    <% recipe.name %>
<% 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

References:
https://github.com/rails/rails/issues/29123
https://stackoverflow.com/questions/44013983/activerecordhasmanythroughordererror

Let me know if that helps :)


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.