Original reflection errors with has_many: via

I am trying to create a system in which users of my site can use selected pages. These pages have two types: clubs or sports. So, I have four models connected as such:

User Model:

class User < ActiveRecord::Base .. has_many :favorites has_many :sports, :through => :favorites has_many :clubs, :through => :favorites .. end 

Featured Model:

 class Favorite < ActiveRecord::Base .. belongs_to :user belongs_to :favoritable, :polymorphic => true end 

Club Model:

 class Club < ActiveRecord::Base .. has_many :favorites, :as => :favoritable has_many :users, :through => :favorites def to_param slug end end 

Sports Model:

 class Sport < ActiveRecord::Base .. def to_param slug end .. has_many :favorites, :as => :favoritable has_many :users, :through => :favorites .. end 

In fact, the user has several sports or clubs through favorites, and the association between favorites, sports and clubs is polymorphic.

In practice, everything works exactly the way I want, and the whole system that I developed works. However, I use Rails_Admin on my site, and I get an error message in three places:

  • At the first boot of the control panel (/ admin). If I refresh the page, it works great.
  • When loading user model in Rails_Admin
  • When loading the Favorites model in Rails_Admin

Here is the error message /admin/user (gist) . All errors are similar, referring to ActiveRecord::Reflection::ThroughReflection#foreign_key delegated to source_reflection.foreign_key, but source_reflection is nil:

Can someone point me in the right direction so that I can fix it? I searched around and asked other programmers / professionals, but no one could detect an error in my models. Thank you very much!

+4
source share
2 answers

Okay, okay, I finally resolved this, and decided that I would post a fix just in case it helps someone else in the future (no one likes to find someone else with the same problem and hasn't sent an answer).

As it turned out, with polymorphic has_many :through , a little more configuration is required. My user model should look like this:

 class User < ActiveRecord::Base .. has_many :favorites has_many :sports, :through => :favorites, :source => :favoritable, :source_type => "Sport" has_many :clubs, :through => :favorites, :source => :favoritable, :source_type => "Club" .. end 

This answer to another question about has_many :through polymorphic associations helped me figure this out.

+10
source

I ran into this error when the code included has_many for an association that does not exist (mid-refactor). Thus, it can also be caused by some common has_many misconfigure. Ruby / Rails code never cares because the dynamic style of Ruby means that associations are called only on demand. But Rails-Admin exhaustively checks properties, which leads to problems with reflection.

+4
source

Source: https://habr.com/ru/post/1482024/


All Articles