Jump to content

The ultimate community for Ruby on Rails developers.


Photo

has_many :through Problem


  • Please log in to reply
1 reply to this topic

#1 Revonik

Revonik

    Passenger

  • Members
  • 2 posts

Posted 13 April 2014 - 11:55 AM

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?

#2 Simply Misunderstood

Simply Misunderstood

    Passenger

  • Members
  • 7 posts

Posted 15 April 2014 - 01:19 AM

In your membership.rb the associations are setup incorrectly.

 

belongs_to needs to be the singular form of the table.

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

Which means Membership belongs to one group and one student.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users