thealbinosmurf
thealbinosmurf

Reputation: 561

Rails Many to many Relationship

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

Answers (2)

Alok Anand
Alok Anand

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 @

guide1

guide2

Upvotes: 1

Agis
Agis

Reputation: 33626

Yes, this is totally valid.

Refer to the guides for more info.

Upvotes: 2

Related Questions