Rails Rich Associations - undefined method error

I have three main models that I work 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 scheme, I would suggest that the Destination model is a connection table that contains information for which users belong to those groups. So, what I'm trying to do using the User object, find out which groups they belong to.

In the Rail console, I do the following:

 me = User.find(1) 

Returns the user object, as expected. Then I try to see which “groups” this user belongs to, which, as I thought, will go through the “Destination” model. But I obviously have something wrong:

 me.groups 

What returns:

 NoMethodError: undefined method `groups' for #<User:0x007fd5d6320c68> 

How do I know which "groups" the "me" object belongs to?

Many thanks!

+4
source share
4 answers

You must declare a User-Groups relationship 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 

In addition, I recommend setting some checks in the Assignment model to so that Assignment always refers to the group and user :

 class Assignment < ActiveRecord::Base belongs_to :group belongs_to :user validates :user_id, presence: true validates :group_id, presence: true end 
+6
source
 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 check out the basics of the association.

+2
source

Your me is of type User not Assignment . Do you want to:

 me.assignments.first.groups 

This will give you all the groups belonging to the user's first assignment. To get all the groups that you could do, as Mr. Yoshiji said, below:

 me.assignments.map(&:groups) 
0
source

You have not defined has_many for groups. Try

 me.assignments.first.group 

must work.

0
source

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


All Articles