简体   繁体   中英

Rails Rich Associations - undefined method error

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

Your me is of type User not Assignment . You want to do:

me.assignments.first.groups

This will give you all the groups belonging to the user's first assignment. To get all the groups you could do as MrYoshiji has commented below:

me.assignments.map(&:groups)

You didn't define a has_many on groups. Try

me.assignments.first.group 

should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM