[RUBY] [Rails] ActiveRecord :: HasManyThrough Order Error in Users # show

environment

Rails 6.0.3.2 ruby 2.6.5p114 (2019-10-01 revision 67812) vscode

Purpose of this article

https://qiita.com/tenitiumai/items/3d9466d7a24197f690bb  The goal is to create a DM function with reference to.

However, this article is intended to show you how to resolve the error. I will omit the procedure for creating a specific DM function (please refer to the reference article above).

Corresponding error

スクリーンショット 2020-09-09 12.51.19.png

Cause of error

Reference article https://qiita.com/krppppp/items/0db4184e9df553f05048 This pays attention to Cannot have a has_many: through association'User # followers' which goes through'User # follower_relationships' before the through associations is defined. Apparently, the model placement order is incorrect. Specifically, it can be inferred that an error has occurred because the followers are loaded before the followers_relationships are loaded.

Solution

Looking at the code,

app/models/user.rb



  has_many :followers, through: :follower_relationships
  
  has_many :follower_relationships, foreign_key: "following_id", class_name: 
  "Relationship", dependent: :destroy
  
  has_many :followings, through: :following_relationships

And followers are above follower_relationships. this

app/models/user.rb



  has_many :followings, through: :following_relationships
  
  has_many :follower_relationships, foreign_key: "following_id", class_name: 
  "Relationship", dependent: :destroy
  
  has_many :followers, through: :follower_relationships

If so, it may be solved. When you access the user details page where the DM button is placed, スクリーンショット 2020-09-09 13.15.47.png

Completed without incident.

in conclusion

I didn't expect the error to occur in the order of the models. From now on, I would like to be aware of that point as well.

Recommended Posts

[Rails] ActiveRecord :: HasManyThrough Order Error in Users # show
Migration error after Activerecord association in Rails5 + Docker environment
ActiveRecord :: NotNullViolation in Devise error
Error in rails db: migrate
[Rails] Unexpected validation error in devise
Show Better Errors in Rails + Docker environment
[Rails] ActiveRecord
[Order method] Set the order of data in Rails
[Rails] Solution when migration error occurs in acts-as-taggable-on
[Rails] Show avatars in posts using Active Storage
500 Internal Server Error occurs in Rails production environment
[Rails] Ranking and pagination in order of likes
Group_by in Rails
One case of solving a migration error in Rails
[Ruby on Rails Tutorial] Error in the test in Chapter 3
Get location information in Rails and sort in ascending order
Arrange posts in order of likes on Rails (ranking)