0

關聯嵌套形式I具有三種模式:軌道4的has_many通過使用AJAX

class Course < ActiveRecord::Base 
    validates :title, presence: true 

    has_many :enrollments 
    has_many :users, through: :enrollments 

    accepts_nested_attributes_for :enrollments 
end 

class Enrollment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :course 

    enum type: { instructor: 0, student: 1 } 
end 

class User < ActiveRecord::Base 
    has_many :enrollments 
    has_many :courses, through: :enrollments 
end 

目前當用戶創建一療程,如預期的那樣創建的關聯(在創建以及登記對象)。不過,我試圖找出最常規的方法爲馬上分配招生對象的類型爲0

因爲我使用作出反應,我的前端框架,我通過一個Ajax請求嘗試此。

var NewCourseForm = React.createClass({ 

    submit: function() { 
    var params = { 
     course: { 
     title: this.refs.title.getDOMNode().value, 
     enrollments_attributes: { 
      type: 0 
     } 
     } 
    }; 

    $.ajax({ 
     type: 'POST', 
     url: '/courses', 
     data: params, 
     success: this.handleData 
    }); 
    }, 

    handleData: function(response) { 
    console.log(response); 
    }, 

    render: function() { 
    return (
     <div> 
     <h1>New Course</h1> 

     <input type='text' placeholder='Title' ref='title' /> 

     <br /> 

     <button onClick={this.submit}>Submit</button> 
     </div> 
    ); 
    } 

}); 

這是我courses_controller.rb

class CoursesController < ApplicationController 
    def index 
    @courses = Course.all 
    end 

    def show 
    @course = Course.find(params[:id]) 
    end 

    def new 
    end 

    def create 
    @course = current_user.courses.create(course_params) 

    respond_to do |format| 
     format.html { redirect_to action: :index } 
     format.json { render json: @course } 
    end 
    end 

    private 

    def course_params 
    params.require(:course).permit(:title, enrollments_attributes: [:type]) 
    end 
end 

現在我得到一個錯誤,指出:

Completed 500 Internal Server Error in 23ms (ActiveRecord: 2.8ms) 

TypeError (no implicit conversion of Symbol into Integer): 

任何幫助,將不勝感激。謝謝!

回答

0

這可能有點晚。但是,爲什麼不在通過ajax傳遞之後將其設置在控制器創建操作中?喜歡的東西

def create 
    @course = current_user.courses.create(course_params) 
    @course.type = 0 

    respond_to do |format| 
     format.html { redirect_to action: :index } 
     format.json { render json: @course } 
end 

您還可以枚舉改變您的註冊類是這樣的:

Class Enrollment 
    enum type: [:teacher, :student] 

上面的代碼會自動分配0和1爲每個角色。隨後,您可以更改模式,以便在註冊時自動分配學生角色。這樣,唯一分配的是在您的註冊控制器中創建創建操作時的老師角色。

t.integer "type",    default: 0