У меня три модели:
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.
Поскольку я использую React в качестве моей front-end framework, я пытаюсь выполнить этот запрос через 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>
);
}
});
Это мой курс_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):
Любая помощь будет оценена по достоинству. Благодарю!
Это может быть немного поздно. Но почему бы вам не настроить его в своем контроллере, чтобы создать действие после его прохождения через 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 каждой роли. Впоследствии вы можете изменить свою схему, чтобы она автоматически присваивала роль учащегося при регистрации. Таким образом, единственное, что назначено, - это роль учителя, когда вы нажимаете на действие create в своем контроллере регистрации.
t.integer "type", default: 0