Search code examples
databaseruby-on-rails-4modelhas-many-throughactive-record-query

has_many :through query between 2 models


I've been searching for hours trying to find a up-to-date example of a mutual has_many :through between 2 models that actually worked, so I finally decided I'd just ask.

My database:

schema.rb

#...
create_table "groups", force: true do |t|
  t.string "group_name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "memberships", force: true do |t|
  t.integer "student_id"
  t.integer "group_id"
end

create_table "students", force: true do |t|
  t.string "user_name"
  t.string "first_name"
  t.string "last_name"
  t.string "password_digest"
  t.datetime "created_at"
  t.datetime "updated_at"
end
#...

My models:

student.rb

class Student < ActiveRecord::Base
  has_secure_password
  validates :password, length: { in: 6..20 }
  validates :user_name, format: {with:/\w{2,7}\.\d{1,4}/}, on: :create
  validates_uniqueness_of :user_name, on: :create
  validates_presence_of :first_name, on: :create
  validates_presence_of :last_name, on: :create
  has_many :memberships,  :dependent => :destroy
  has_many :groups, through: :memberships
  has_many :ratings,  :dependent => :destroy
end

group.rb

class Group < ActiveRecord::Base
  has_many :memberships, :dependent => :destroy
  has_many :students, through: :memberships
  validates_uniqueness_of :group_name
end

membership.rb

class Membership < ActiveRecord::Base
  belongs_to :students
  belongs_to :groups
end

If my authorization correctly puts the logged-in student's :user_name into session[:user_name] if I wanted to get all of the groups to which that student belonged, what would be the proper line(s)? I'm also interested in finding the students within a given group.

I tried:

 @current_student = Student.find_by_user_name(session[:user_name])
 @current_groups = @current_student.groups

But I was given:

uninitialized constant Student::Groups

What did I do wrong?


Solution

  • Change membership.rb to :

    class Membership < ActiveRecord::Base
      belongs_to :student
      belongs_to :group
    end