您能解释一下我如何从Rails应用程序中创建的关联中删除这些复制吗?该应用程序允许用户教授不同的课程,以及学习不同的课程。可供学习的课程与可供教授的课程相同。为了这个问题,假设有3门课程可以教和学习,science, math, english
我目前拥有这些协会的方式如下。我创建了一个目标模型(它代表了可供学习的课程),并播种了三门课程,science, math, english。我还创建了一个这样的课程模型(它代表了用户正在教授的课程),并播种了同样的三门课程。注意,如果不清楚,我将模型命名为"Target“,因为它代表了用户试图学习的主题。
User
has_and_belongs_to_many :targets #courses the user is studying
has_and_belongs_to_many :courses #courses that users are teaching因此,我相信我有一些不必要的重复。课程和目标模型将有完全相同的数据(即相同的课程)。是否有一种方法来创建一个模型(代替两个Target.rb和Course.rb)并使用它来表示用户正在教和学习的两个课程?
更新
为了帮助澄清,我只是引用种子数据来帮助解释/显示模型正在做什么,即Target.rb和Course.rb本质上是相同的,只是扮演着不同的角色。它更像是用户与目标/课程之间未来关系的模板。例如,我可能在学科学,但在教数学。
发布于 2013-08-11 01:27:11
下面的解决方案。你确定你想在学生和课程之间建立one_to_many联系--这似乎是显而易见的--多到多。不管怎么说,重要的一点是第二关联。
class User
has_and_belongs_to_many :courses #or possibly better has_many :through, your call
has_many :taught_courses, :class_name => :course, :foreign_key => teacher_id
end
class Course
belongs_to :teacher, :class_name => :user, :foreign_key => teacher_id
has_and_belongs_to_many :users
end更新:
上面的代码将创建两个关联。第一个是habtm关联,它需要另一个名为courses_users的表,它有两个列(course_id和user_id,没有id列)。这将给你:
course.users #=> list of users taking the course如果需要,可以重命名此关联写作:
has_and_belongs_to_many :students, :class_name => :user第二个关联是one_to_many,因此您可以通过以下方法来使用它:
course.teacher #=> return single user or nil
user.taught_courses #=> return list of courses taught by given user另一项最新情况:
通过两个表进行多个habtm关联(您可以更喜欢一个表,但随后需要使用has_many : this,这在本例中可能更好)。模式:
create_table "courses" do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "courses_students", :id => false do |t|
t.integer "course_id"
t.integer "user_id"
end
create_table "courses_teachers", :id => false do |t|
t.integer "course_id"
t.integer "user_id"
end
create_table "users" do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end型号:
class Course < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :teachers, :class_name => "User", :join_table => :courses_teachers
has_and_belongs_to_many :students, :class_name => "User", :join_table => :courses_students
end
class User < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :courses, :join_table => :courses_students
has_and_belongs_to_many :taught_corses, :join_table => :courses_teachers
end发布于 2013-08-11 01:32:43
听起来你好像有课程。
class Course < ActiveRecord::Base
attr_accessible :subject
has_and_belongs_to_many :students
belongs_to :teacher
end在此设计中,一门课程可以有许多学生注册,学生可以注册任意数量的课程。每门课都可以指定一名教师。一个课程将有一个(字符串)属性,名为subject,如“数学”或“英语”。课程模型可以扩展到包含额外的信息,如教室数量、难度、长度等。
这将允许查询,例如
alice = Student.find_by_first_name("Alice")
alice.courses.last.subject
=> "english"
alice.courses.last.teacher.first_name
=> "Eric"或
eric = Teacher.find_by_first_name("Eric")
eric.courses.where(subject: 'math').count
=> 3这表明埃里克在教三节数学课。
https://stackoverflow.com/questions/18167814
复制相似问题