Search code examples
ruby-on-railsactiverecordhas-many-throughactiverecord-relation

Rails: Cannot have a has_many :through association before association is defined


Upgrading an app from Rails 4.2.9 to Rails 5.2.1.

Through much of the nasty part updating dependencies & whatnot and finally have app running in the console and now trying to hit pages on server. Some pages load but others:

Cannot have a has_many :through association 'User#clubs' which goes through 'User#memberships' before the through association is defined.

Not clear what may have changed in Rails 5 to trigger this? Not even sure where to start looking.

Thoughts?

Seems to fail on line called out below:

class ViewableStories
  ...
  def for_user
    Story
      .includes(:publications)
      .references(:publications)
      .where(
        stories[:user_id]
        .eq(@user.id)
        .or(
          publications[:club_id]
          .in(@user.club_ids)        <<==== execution halts
          .and(
            publications[:publish_on]
            .lt(Date.today)
            .or(publications[:publish_on].eq(nil))
          )
        )
      )
  end
end

Which is called from model/story.rb

  def self.viewable_published_stories_for(user)
    ViewableStories
      .for_user(user)
      .includes(:cover_image, :user, :table_of_contents)
      .published
      .chronological
  end

Solution

  • It is probably just an ordering issue in your model. The has_many has to come before the has_many through.

    So right now, you probably have:

    class User < ApplicationRecord
      ...
      has_many :clubs, through: :memberships
      has_many :memberships
      ...
    end
    

    You just need to move the has_many :memberships above the has_many through:

    class User < ApplicationRecord
      ...
      has_many :memberships
      has_many :clubs, through: :memberships
      ...
    end