【问题标题】:Rails 4 has_many through association nested form using ajaxRails 4 has_many 通过使用 ajax 的关联嵌套形式
【发布时间】:2015-06-23 03:06:04
【问题描述】:

我有三个模型:

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>
    );
  }

});

这是我的课程_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):

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

【问题讨论】:

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


    【解决方案1】:

    这可能有点晚了。但是为什么不在通过 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
    

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      相关资源
      最近更新 更多