Rails has_many associations

2019-09-06 20:32发布

问题:

Considering the following models, how can I select only the notes of students owned by a user? Also, do the models look ok?

class Student < ActiveRecord::Base
    has_many :student_notes
    has_many :notes, :through => :student_notes

    has_many :relationships
    has_many :users, :through => :relationships
end

class Note < ActiveRecord::Base
    has_many :student_notes
    has_many :students, :through => :student_notes
end

class StudentNote < ActiveRecord::Base
    belongs_to :student
    belongs_to :note
end

class User < ActiveRecord::Base
    has_many :relationships
    has_many :students, :through => :relationships
end

class Relationship < ActiveRecord::Base
  belongs_to :student
  belongs_to :user
end

Thanks in advance!

回答1:

You could simplify your models cutting off StudentNoteand Relationship and using the has_and_belongs_to_many association instead.

To select only the notes of students owned by a user, you could add has_many :notes, :through => :students to your User model

Your models should look like this:

class Student < ActiveRecord::Base
    has_and_belongs_to_many :notes
    has_and_belongs_to_many :users
end

class Note < ActiveRecord::Base
    has_and_belongs_to_many :students
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :students
    has_many :notes, :through => :students
end

And you could select the notes of students owned by a user this way:

some_user.notes



回答2:

You can simply add notes relation:

class User < ActiveRecord::Base
  has_many :relationships
  has_many :students, :through => :relationships

  # new relation
  has_many :notes, :through => :students
end

and query:

my_user.notes