简体   繁体   English

用户has_many:课程,但课程不属于:用户

[英]user has_many :courses, but course doesn't belong_to :user

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? 考虑一下,我假设这是因为我需要除has_many之外的另一种关系? Like HABTM? 喜欢HABTM吗?

I think I'm confused about how AR associations work... 我想我对AR关联的工作方式感到困惑...

user.rb 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 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_id column from courses and course_id from users. 您应该使用HABTM,也可以从课程中删除user_id列,并从用户中删除course_id

class User < ActiveRecord::Base
  has_many :course_users
  has_many :course, :through => :course_users
end

class Course < ActiveRecord::Base
  has_many :course_users
  has_many :users, :through => :course_users
end

class CourseUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :course
# == Schema Information
#
# Table name: course_users
#
#  id          :integer         not null, primary key
#  created_at  :datetime        not null
#  updated_at  :datetime        not null
#  user_id     :integer
#  course_id     :integer
#
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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