【问题标题】:I need help to solve relationship error and list options in a second select, according to the value entered in the first select根据第一次选择中输入的值,我需要帮助解决第二次选择中的关系错误和列表选项
【发布时间】:2019-09-14 04:27:55
【问题描述】:

根据第一次选择中输入的值,我需要帮助解决第二次选择中的关系错误和列表选项

在浏览器控制台中选择第一个“选择”时出现以下错误。

get_communes?selected_region=ATACAMA:1 加载资源失败:服务器响应状态为 401(未授权)

我的目标是在第一次选择中选择一个区域,然后在第二次选择该区域中的选项

我正在使用 ruby​​ on rails、javascript、jQuery、bootstrap

request.js

$(document).on("turbolinks:load", function() {


    //============ traer comuna de acuerdo a la region 
    $('#request_region').on('change', function (e) {
        var request_region = $('#request_region').find(":selected").text();
        $.ajax({
            url: '/requests/get_communes',
            type: 'get',
            data: {selected_region: request_region},
            success: function(data) {
                console.log('correcto!!');

                console.log(data);


                $("#request_commune").children().remove();
                var listitems = []; 
                $.each(data, function(key, value) { 
                    listitems += '<option value="' + value['id']+ '">' + value['name'] + '</option>'; 
                }); 
                $("#request_commune").append(listitems);
            }
        });
    });


    $(".js-example-basic-single").select2();

});

new.html.erb

            <div class="col-12 col-md-6">
                <%= f.select :region_id, @regions, {include_blank: 'Elija una región'}, {class: 'js-example-basic-single', id: :request_region, required: true} %>
                <%= f.label :Región, class:'' %>
            </div>


            <div class="col-12 col-md-6">

                    <span class="custom-dropdown last">
                        <select class="js-example-basic-single" id="request_commune" data-live-search="true" name="request[commune_id]"
                        required>
                        <option value="AL">Primero Elija una Región</option>
                    </select>
                    <%= f.label :comuna, class:'' %>

            </div>

文件夹:请求(设计) registrations_controller-rb

    def new
        @regions = Region.all.collect { |reg| [reg.name, reg.id] }
        super
    end


requests_controller.rb

class RequestsController < ApplicationController
  before_action :authenticate_request!
  before_action :set_request, only: [:show, :edit, :update] # probably want to keep using this

  # GET /users
  # GET /users.json
  def index
    @requests = Request.all
  end

  # # GET /users/1
  # # GET /users/1.json
  def show

  end

  # GET /users/1/edit
  def edit

  end

  # # PATCH/PUT /users/1
  # # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  #def dashboard
    #corregir este método
    #data_certificacion = Event.find_by(request: current_request)
    #byebug
    #if data_certificacion.present?
     # @certification = true
    #end
  #end


  def get_communes
        region = Region.find_by(name: params[:selected_region])
        @communes = Commune.order(name: :asc).where(region_id: region.id)
    render json: @communes
  end


  private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @request = Request.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:request).permit(:role, :name)
  end

end

关系和模型

region:
  has_many :communes

commune
  belongs_to :region
  has_many :requests

Schema:


  create_table "requests", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    t.integer "failed_attempts", default: 0, null: false
    t.string "unlock_token"
    t.datetime "locked_at"
    t.string "name"
    t.integer "phone"
    t.text "comment"
    t.boolean "state"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "region_id"
    t.bigint "commune_id"
    t.index ["commune_id"], name: "index_requests_on_commune_id"
    t.index ["email"], name: "index_requests_on_email", unique: true
    t.index ["region_id"], name: "index_requests_on_region_id"
    t.index ["reset_password_token"], name: "index_requests_on_reset_password_token", unique: true
  end


  create_table "regions", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end


  create_table "communes", force: :cascade do |t|
    t.string "name"
    t.bigint "region_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["region_id"], name: "index_communes_on_region_id"
  end

【问题讨论】:

  • 当你的服务器返回401 (Unauthorized)时,是什么让你认为这是一个关系错误?
  • @jvillian 我不确定,服务器显示以下内容:Started GET "/requests/get_communes?Selected_region = ATACAMA" for :: 1 at 2019-04-24 15:21:21 - 0400 RequestsController 处理 # get_communes as * / * 参数:{"selected_region" => "ATACAMA"} Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
  • 您的ApplicationController 是否也包括before_action :authenticate_request!

标签: jquery ruby-on-rails ruby postgresql ruby-on-rails-4


【解决方案1】:

似乎您需要生成身份验证令牌并将其传递给 ajax 调用,例如:

beforeSend: function (xhr) {
   xhr.setRequestHeader ("Authorization", token ));
},

检查 jQuery 的 beforeSend 指令。

【讨论】:

  • 出于好奇...这需要,不是吗,token 在客户端可用?而且,如果是这样,这是否意味着任何想在浏览器中查看 js 代码的人都可以使用token
  • 它需要一种机制来为每个用户生成一个唯一的令牌(也许使用不对称的 jwt?)。所以即使他看源代码,他也会看到自己的令牌。这是必需的,因为他试图从受保护的源中检索 ajax 数据。
【解决方案2】:

我认为你有什么问题在这里before_action: authenticate_request!,我想如果你从你的控制器中删除这段代码,你的get_communes 会返回给你 JSON!

“before_action :authenticate_request!”假设仅在AuthenticationControllerApplicationController 中使用!

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2020-08-28
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多