ruby-on-rails - 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
如何确定这种嵌套关系的范围?
解决方案
推荐阅读
- sharepoint-online - 从移动应用程序访问共享点在线列表
- alfresco - org.alfresco.trashcan.TrashcanCleanerTest 中的 java.lang.ExceptionInInitializerError。
(TrashcanCleanerTest.java:67) - maven - Maven - 使用从 src/test 到 src/main 的静态变量
- spring-boot - Spring Boot WAR部署到tomcat
- windows - 将文件从 Jenkins 服务器 (Linux) 复制到 Windows 2003 共享位置
- rest - Cisco Spark:有没有办法使用 bot API 进行@all 提及?
- excel - 将 Excel 工作表打印成单个 PDF
- c# - 来自 ASP.NET SmtpClient 的偶尔“SMTP 服务器需要安全连接”
- regex - 和 REGEX 中的运算符
- python - 如何在样条插值的所有数据点处设置导数零约束?