Rails 4 has_many通过使用ajax的关联嵌套表单

时间:2015-06-23 03:06:04

标签: ruby-on-rails ajax reactjs nested-attributes has-many-through

我有三种模式:

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作为我的前端框架,所以我尝试通过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):

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

这可能有点晚了。但是为什么不在通过ajax传递后在控制器创建动作中设置它?像

这样的东西
class Player(object):
    def __init__(self, name, hp, dmg, lvl, inventory, speed):
       self.name = name
       self.hp = hp
       self.dmg = dmg
       self.lvl = lvl
       self.inventory = inventory
       self.speed = speed

    def printStats(self):
       return("Health: " + self.hp + ", Attack Damage: " + self.dmg + ", Level: " + self.lvl + ", Speed: " + self.speed)

link = Player("Link", 10, 3, 1, {}, 3)
link.printStats

您还可以使用枚举更改您的注册课程:

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

上面的代码自动为每个角色分配0和1。随后,您可以更改架构,以便在注册时自动分配学生角色。这样,分配的唯一内容就是在您的注册控制器中点击创建操作时的教师角色。

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