首页 > 解决方案 > Rails 5控制器中的范围嵌套关联

问题描述

我正在尝试在 Rails 5 中“修复”来自制动器的 Unscoped Find 警告。

问题是我有嵌套关系,并且在运行刹车后我意识到我可以访问数据库中没有范围的任何对象。

我的模型中有这种关系:

class Medic < ApplicationRecord
  has_many :patients, dependent: :destroy
  validates_associated :patients
end

class Patient < ApplicationRecord
  belongs_to :medic
  has_many :consultations, dependent: :destroy
  accepts_nested_attributes_for :consultations
  validates_associated :consultations
end

class Consultation < ApplicationRecord
  belongs_to :patient
  has_many :prescriptions, dependent: :destroy
  accepts_nested_attributes_for :prescriptions
  validates_associated :prescriptions
end

所以,当我尝试在控制器中的回调范围内,通过这种方式:

控制器/患者控制器.rb

  private
    def set_patient
      @patient = current_medic.patients.find(params[:id]) # this scope works
    end

控制器/consultations_controller.rb

  before_action :set_patient
  before_action :set_consultation, only: [:show, :edit, :update, :destroy]
  ...code...
  private
    def set_consultation
      @consultation = @patient.consultations.find(params[:id])
    end

    def set_patient
      @patient = current_medic.patients.find_by_id(params[:patient_id])
    end

@consultation = @patient.consultations.find(params[:id])这个范围不起作用“ undefined method `consultations' for nil:NilClass ”只有在我做 Consultation.find(params[:id]) 时才有效,但是这样,如果将 X id 作为参数 /consultations/3 ,任何人都可以访问任何咨询,尽管该咨询不属于与用户关联的任何患者

控制器/prescriptions_controller.rb

  before_action :set_consultation
  before_action :set_prescription, only: [:show, :edit, :update, :destroy]
  ...code...
  private
  def set_prescription
    @prescription = Prescription.find(params[:id]) # the same here, object consultation is 'nil' @consultation.prescriptions.find(params[:id]) won't work
  end

  def set_consultation
    @consultation = Consultation.find_by_id(params[:consultation_id])
  end

我的测试在显示、编辑、更新和销毁方面都失败了。例如。

带有 minitest 的consults_controller_test.rb

  test "should show consultation" do
    get consultation_url(id: @consultation.id)
    assert_response :success # expected response 2XX but get error 500
  end

我的路线文件:

Rails.application.routes.draw do
  devise_for :medics

  resources :patients, shallow: true do
    resources :consultations
  end

  resources :consultations, shallow: true do
    resources :prescriptions
  end
end

如何确定这种嵌套关系的范围?

标签: ruby-on-railsruby

解决方案


推荐阅读