【问题标题】:Rails: Assigning another user to an excisting entry (associations)Rails:将另一个用户分配给现有条目(关联)
【发布时间】:2016-07-06 19:03:33
【问题描述】:

我的项目中有 2 个模型。 1 是用户,1 是课程。 一个用户有很多课程 课程有很多用户。 主要问题是我无法弄清楚如何在不创建新课程的情况下将用户分配给课程。

user = User.first 
course = Course.new(title:"course01")

然后我的输出将类似于

Course id: 2, title: "course01", created_at: "2016-03-20 07:05:23",            
updated_at: "2016-03-20 07:05:23", user_id: 1>

现在我不知道如何在同一课程中添加其他用户。

user = User.second
?

【问题讨论】:

  • 阅读 has_many :through type of association here has_many :through association 希望这个链接能引导你走向正确的方向。
  • 将 user_id 分配给课程有效。我只是不知道如何添加另一个用户,所以同样的课程。
  • 你需要一个模型来连接用户和课程,这可以通过 has_many :though 关联来实现。
  • 你完全正确。这对我有帮助:stackoverflow.com/questions/11600928/…
  • 你必须在课程和用户之间建立HABTM关系

标签: ruby-on-rails associations


【解决方案1】:

courses 表中删除user_id,不需要它

为 HABTM 创建连接表

create_table :users_courses, id: false do |t|
  t.references :course
  t.references :user
end

user.rb 文件中

has_and_belongs_to_many :courses

course.rb 文件中

has_and_belongs_to_many :users

创建新课程后

course = Course.create(title:"course01")
users = User.all or whatever you need to assign to same course
users.each do |user|
  course.users << user ##assign 
end

在 Rails 控制台中

course = Course.first or Course.find(1) or whatever you want 
course.users << User.find(1) or whatever you want

【讨论】:

  • 谢谢!如果我想在 Rails 控制台中手动将用户分配给课程,代码是什么?
【解决方案2】:

假设在将用户分配到课程时创建了一个新的“UserCourseAssignment”。

您可以使用属性 user_id 和 course_id 创建一个新的 UserCourseAssignment 模型来存储哪些用户被分配到哪些课程。每次将用户分配到课程时,此新表都会有一个新条目。

用户模型

has_many :user_course_assignments

has_many :courses, through: :user_course_assignments

课程模式

has_many :user_course_assignments

has_many :users, though: :user_course_assignments

UserCourseAssignment 模型

belongs_to :user
belongs_to :course

编辑: 我认为您目前在 Course 模型中有 user_id 属性。实现 has_many :through 关联后就不需要它了。

【讨论】:

  • 谢谢,还有一个问题我已经创建了一门课程并为它分配了一个用户。在我的代码中,我只想在用户尚未注册时分配。我有这个,但我希望只有在 current_user 尚未分配给这门课程时才会发生:def beginerscourse_01 user = current_user course = Course.find(5) user.courses
  • 在这种情况下,除非课程已经在 current_user 的注册中,否则请进行分配。像这样 - def beginnerscourse_01 course = Course.find(5) unless current_user.user_course_assignments.find_by(course_id: course.id) # Enroll end end
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
相关资源
最近更新 更多