I have three basic models that I am working with:
class User < ActiveRecord::Base
has_many :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
class Group < ActiveRecord::Base
has_many :assignments
end
Using this schema, I would assume the "Assignment" model is sort of the join table, which holds the information for which users belong to which groups. So, what I am trying to do is, using a User object, find out what groups they belong to.
In Rail console, I am doing the following:
me = User.find(1)
Which returns the user object, as it should. Then, I attempt to see which "groups" this user belongs to, which I thought it would go through the "Assignment" model. But, I'm obviously doing something wrong:
me.groups
Which returns:
NoMethodError: undefined method `groups' for #<User:0x007fd5d6320c68>
How would I go about finding out which "groups" the "me" object belongs to?
Thanks very much!
You have to declare the User - Groups relation in each model:
class User < ActiveRecord::Base
has_many :assignments
has_many :groups, through: :assignments
end
class Group < ActiveRecord::Base
has_many :assignments
has_many :users, through: :assignments
end
Also, I recommend you to set some validations on the Assignment model to make sure an Assignment always refers to a Group AND a User:
class Assignment < ActiveRecord::Base
belongs_to :group
belongs_to :user
validates :user_id, presence: true
validates :group_id, presence: true
end
class User < ActiveRecord::Base
has_many :assignments
has_many :groups, through: :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
class Group < ActiveRecord::Base
has_many :assignments
has_many :users, through: :assignments
end
Please refer association basics
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With