Reputation: 561
This may be simple but I was not sure if this is possible. The question is about the group.rb
model if it is possible to have_many
of a model that does not exist if it is through another model. Thanks for the help.
# app/models/user.rb
class User < ActiveRecord::Base
has_many :admin_groups
has_many :groups
end
# app/models/group.rb
class Group < ActiveRecord::Base
has_many :admin_groups
has_many :admins, through: :admin_groups
end
# app/models/admin_group.rb
class AdminGroup < ActiveRecord::Base
belongs_to :group
belongs_to :admin, class_name: "User", foreign_key: "user_id"
end
Upvotes: 1
Views: 54
Reputation: 3356
You can refer an associated model by name of your choice and use 'class_name' option to relate that reference name with real model as shown in your own code, and yes you can have (has_many, through) association with a model on just reference name while using 'class_name' option.
Follow these 2 links @
Upvotes: 1