【问题标题】:Can't create new database entry from form submission无法从表单提交创建新的数据库条目
【发布时间】:2016-02-22 01:14:07
【问题描述】:

我有这样的用户和配对模型:

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

以及架构中的相关部分(删除了大小的设计字段):

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

我有一个表单视图,其中包含 1 个列出所有学生的下拉框和 1 个列出所有主管的下拉框。我的目标是双重的:

(1) 一旦从框中选择了主管和学生,获取他们的 id 并将主管的 id 分配给学生的 supervisor_id 列。 (使用 AJAX 补丁请求完成)

(2) 在配对表中使用下拉列表中的 id 创建一个新行。 (通过pairings_controllers create方法完成)

这是我的看法:

<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 %>

还有控制器:

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

我遇到的问题是脚本没有成功,但仍设法更新 supervisor_id 字段。我尝试在没有脚本的情况下进行测试,看看是否会创建配对表条目,但它仍然没有,因为接收到来自表单的参数,但一旦按下按钮就不会提交给事务。不知道该怎么做真的很感激任何帮助!

【问题讨论】:

  • 在浏览器中打开控制台(在开发人员工具下)并单击按钮以触发 Ajax。浏览器控制台出现什么错误?
  • 控制台没有显示错误,只说 XHR 完成加载:PATCH。即使用户表中的 supervisor_id 字段按应有的方式更新,脚本似乎也没有成功并完成执行。这会影响控制器以某种方式创建动作

标签: javascript ruby-on-rails ruby ajax ruby-on-rails-4


【解决方案1】:

您需要定义控制器响应 .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

或类似的东西。

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

【讨论】:

    【解决方案2】:

    通过以下更改解决

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

    Routes.rb

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多