17

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
Meltemi
  • 37,979
  • 50
  • 195
  • 293

1 Answers1

28

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
AbM
  • 7,326
  • 2
  • 25
  • 28
  • 4
    Yup. it was that simple! Thanks! But this wasn't the case in Rails 4.x. Can't seem to find where this change is documented. If anyone knows please post. Like to know what I overlooked. Thanks again! – Meltemi Oct 31 '18 at 00:28
  • I have a Rails 5.0 app that I just upgraded to 5.2. I got the same error & applied this solution which solved my problem. – Pamela Cook - LightBe Corp Jan 29 '22 at 18:23