I’ve been struggling with something that’s probably very obvious:
When I try and assign courses to users, I don’t think it’s allowing for a course to be in the collection of more than one user.
I have a method which iterates through every user and assigns a subsection of every course to that user. Only the last few users have courses assigned to them. I think this is because the relationship between the two is stored as a field in the courses table, so a course can only belong to one user. I want courses to belong to many users.
Thinking about it, I’m assuming this is because I need another kind of relationship than has_many? Like HABTM?
I think I’m confused about how AR associations work…
user.rb
class User < ActiveRecord::Base
has_many :courses
has_many :bookmarks, :class_name => 'Course'
attr_accessible :email, :password, :courses, :bookmarks
validates_presence_of :password, :on => :create
validates_presence_of :email, :on => :create
validates :password, :length => { :in => 6..20 }
validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
validates_uniqueness_of :email
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# password_digest :string(255)
# course_id :integer
# bookmark_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
course.rb
class Course < ActiveRecord::Base
attr_accessible :name
end
# == Schema Information
#
# Table name: courses
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer
#
You should go with HABTM, also you can delete
user_idcolumn from courses andcourse_idfrom users.