简体   繁体   English

无法通过表单提交创建新的数据库条目

[英]Can't create new database entry from form submission

I have User and Pairings models as such: 我有这样的用户和配对模型:

class User < ActiveRecord::Base

  enum role: [:student, :supervisor, :admin]
has_many :students, class_name: "User",
                      foreign_key: "supervisor_id"

  belongs_to :supervisor, class_name: "User"

  has_and_belongs_to_many :pairings
end

class Pairing < ActiveRecord::Base

  has_and_belongs_to_many :supervisor, class_name: 'User'
  belongs_to :student, class_name: 'User'

end

And the related parts from schema (removed devise fields for size): 以及架构中的相关部分(已删除大小的设计字段):

ActiveRecord::Schema.define(version: 20160221222318) do
create_table "pairings", force: :cascade do |t|
    t.integer  "supervisor_id"
    t.integer  "student_id"
    t.string   "project_title"
  end

  add_index "pairings", ["student_id"], name: "index_pairings_on_student_id", unique: true
  add_index "pairings", ["supervisor_id"], name: "index_pairings_on_supervisor_id"

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.integer  "role"
    t.integer  "supervisor_id"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true

end

I have a view with a form which holds 1 dropdown box listing all students and 1 listing all supervisors. 我有一个带有一个表格的视图,该表格包含一个列出所有学生的下拉框和一个列出所有主管的下拉框。 My goal is twofold: 我的目标是双重的:

(1) once a supervisor and student are selected from the boxes, get their ids and asssign the id of the supervisor to the supervisor_id column of the student. (1)从框中选择主管和学生后,获取其ID并将主管的ID分配给学生的supervisor_id列。 (Done using AJAX Patch request) (使用AJAX补丁请求完成)

(2) crate a new row in the pairings table with the ids from the dropdowns. (2)使用下拉列表中的ID在配对表中创建一个新行。 (Done through the pairings_controllers create method) (通过pairings_controllers创建方法完成)

This is my view: 这是我的看法:

<script>

$("#my_special_form").submit(function(){
  var url = "/users/" + this.elements["pairing[student_id]"].value;

  $.ajax(url, {
    beforeSend: $.rails.CSRFProtection,
    data: {
      user: {
        supervisor_id: this.elements["pairing[supervisor_id]"].value
      }
    },
    type: 'PATCH',
    dataType: 'JSON',
    success: function(data, textStatus, jqXHR) {
      console.log('Success', data, textStatus, jqXHR);
    },
  });

  return false; // cancels out the normal form submission
});

</script>


<%= form_for(Pairing.new, url: pairings_path, method: :post, html: { id: 'my_special_form' }) do |f| %>
  <div class="field">
    <%= f.label :supervisor_id %>
    <%= f.collection_select(:supervisor_id, User.where(role: 1), :id, :name) %>
  </div>
  <div class="field">
    <%= f.label :student_id %>
    <%= f.collection_select(:student_id, User.where(role: 0), :id, :name) %>
  </div>
  <div class ="field">
    <%= f.label :project_title %>
    <%= f.text_field :project_title %>
  <%= f.submit %>
<% end %>

And the controllers: 和控制器:

class PairingsController < ApplicationController
    def new
        @pairing = Pairing.new
    end

  def create
    @pairing = Pairing.new(pair_params)
  end

  def update
    @pairing = Pairing.find(params[:id])
    @pairing.update_attributes(pairing_params)
  end

  private
    def pair_params
      params.require(:pairing).permit(:supervisor_id, :student_id, :project_title)
    end
end

class UsersController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def index
    @users = User.all
    authorize User
  end

  def show
    @user = User.find(params[:id])
    authorize @user
  end

  def update
    @user = User.find(params[:id])
    authorize @user
    if @user.update_attributes(secure_params)
      redirect_to users_path, :notice => "User updated."
    else
      redirect_to users_path, :alert => "Unable to update user."
    end
  end

  private

  def secure_params
    params.require(:user).permit(:role, :supervisor_id)
  end

end

The problem I'm having is that the script doesn't succeed but still manages to update the supervisor_id field. 我遇到的问题是脚本无法成功执行,但是仍然可以更新supervisor_id字段。 I tried testing without the script to see if the pairing table entry would get created and it still hasn't as the parameters from the forms are received but aren't committed to the transaction once the button is pressed. 我尝试在没有脚本的情况下进行测试,以查看是否会创建配对表条目,但仍然没有,因为从表单接收到参数后,一旦按下按钮,它们就不会提交给事务。 Don't know what to do really any help is appreciated ! 不知道该怎么办,真的可以得到任何帮助!

You need to define that the controller responds to .json and return a status code. 您需要定义控制器响应.json并返回状态代码。

respond_to do |format|
    if @user.update_attributes(secure_params)
      flash[:notice] = 'User was successfully edited.'
      format.html { render action: :index }
      format.json { render xml: @user, status: 200 }
    else
      format.html { render action: @user }
      format.json { render xml: @user.errors, status: :unprocessable_entity }
    end
  end
end

or something to that effect. 或类似的东西。

http://edgeapi.rubyonrails.org/classes/ActionController/Responder.html http://edgeapi.rubyonrails.org/classes/ActionController/Responder.html

Solved by doing the following changes 通过进行以下更改来解决

<%= form_for(Pairing.new, url: new_pairing_path, method: :post, html: { id: 'pairing_form' }) do |f| %>

Routes.rb Routes.rb

match '/pairings/new', to: 'pairings#create', via: [:post]
match '/users/update', to: 'users#update', via: [:patch]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM