has_many :through uninitialized constant

a 夏天 提交于 2019-12-03 02:49:24
Richard Peck

The problem I can see is your naming of GroupUser

We use join models all the time, and we also name them with an underscore:

group_user.rb
class GroupUser < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

The uninitialized constant error will be caused by the model not loading correctly, which I imagine will be due to the naming issue. If that doesn't work, you should reference the model with the :class_name parameter in your relation declarations:

  has_many :group_users, :class_name => 'GroupUser'
  has_many :groups, :through => :group_users

Update

We wanted to call extra attributes from the join model, and found this way:

#app/models/message.rb
has_many :image_messages, :class_name => 'ImageMessage'
has_many :images, -> { select("#{Image.table_name}.*, #{ImageMessage.table_name}.caption AS caption") }, :class_name => 'Image', :through => :image_messages, dependent: :destroy

This uses the select method which you can use when you created an ActiveRecord association, and as we discovered from this RailsCast, you can use that to create alias columns in your queries

For you, you may wish to try this:

#app/models/user.rb
has_many :group_users, :class_name => 'Groupuser'
has_many :groups, -> { select("#{User.table_name}.*, #{Groupuser.table_name}.status AS status") }, :class_name => 'Group', :through => :group_users, dependent: :destroy
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!