【问题标题】:Rails creating through via associationRails 通过关联创建
【发布时间】:2015-09-21 21:29:52
【问题描述】:

学生模型:

class Student < ActiveRecord::Base
  has_many :courses
end

课程模式:

class Course < ActiveRecord::Base
  belongs_to :student
end

如何通过学生创建课程,以便获得 [Course id: 1, student_id: 1]。我尝试了以下方法,但它给了我 student_id nil。

课程负责人:

@course = Student.find(params[:id])
@course = @course.new(params[:course])

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3.2


    【解决方案1】:

    你的解决方案有几个小问题,但如果我很好地理解你想要做什么,这基本上是在课程控制器的某个操作中创建与学生相关联的课程对象,你需要做的就是添加这些行吃course_controller 操作:

    课程控制器:

    class CoursesController < ApplicationController
    
      ...
    
      def new
        @student = Student.find(params[:student_id])
        @course = Course.new student_id: @student.id
      end 
    
      def create
        @course = Course.new(params[:course])
        @course.save
      end
    
      ... 
    
    end
    

    在您调用 new_course_path 的视图中,您应该传递 :student_id 值,如下例所示:

    new_course_path(student_id: @student.id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      相关资源
      最近更新 更多