你好,美丽的社区。我是Rails的新手,我有一个项目,我必须注册病人,每个病人都有进展。我已经能够在数据库中注册并保存患者,但我无法保存这些患者的演变记录。
我将展示我的代码给任何有能力和想要指导我的人。我将不胜感激
#BACK OFFICE ROUTES-PACIENTES
resources :patients do
resources :evolutions
end
CONTROLLERS:
class PatientsController < ApplicationController
def create
@patient = current_user.patients.new patient_params
if @patient.save
return redirect_to patients_url, notice: 'El paciente fue agregado con exito'
end
render :new
end
class EvolutionsController < ApplicationController
before_action :authenticate_user!
def index
@evolutions = @patient.Evolution.all
end
def new
@evolution = Evolution.new
end
def edit
end
def create
@evolution = current_user.evolutions.new evolution_params
if @evolution.save
return redirect_to patients_url, notice: 'La evolucion fue agregada con exito'
end
render :new
end
def show
@evolution = Evolution.find params[:id]
end
private
def evolution_params
params.require(:evolution).permit(:motivo, :evolution, :patient_id)
end
end正如我所说的,病人没有问题,但我不能将进化保存在数据库中。
发布于 2021-06-30 14:41:05
我希望你的ApplicationController已经有了一个before_action :authenticate_user!,否则current_user不会在你的PatientsController中工作。所以,你可以把它去掉。
在您的Evolutions#index操作中,您将引用实例变量@patient,尽管没有在任何地方设置该变量。根据您的路由,这是Patient下的嵌套资源,因此您的index操作应该如下所示:
def index
@patient = Patient.find(params[:patient_id]
@evolutions = @patient.evolutions # You could skip this and just use @patient.evolutions in your view if you like
end同样,应该修改您的new操作,以便为特定患者生成新的进化:
def new
@patient = Patient.find(params[:patient_id]
@evolution = @patient.evolutions.build
end这将创建一个新的未保存的Evolution实例,该实例已经属于适当的用户。
最后,我们还需要更新create操作来处理嵌套的资源:
def create
@patient = Patient.find(params[:patient_id]
@evolution = @patient.evolutions.build(evolution_params)
if @evolution.save
redirect_to patients_url, notice: 'La evolucion fue agregada con exito'
else
render :new
end
end正如您所看到的,我们现在在操作中有了重复的代码,用于从参数中查找Patient……我们可以通过将它移到操作前来使它变得干爽。
把所有这些放在一起:
class EvolutionsController < ApplicationController
before_action :load_patient
def index
@evolutions = @patient.evolutions # You could skip this and just use @patient.evolutions in your view if you like
end
def show
@evolution = @patient.evolutions.find(params[:id])
end
def new
@evolution = @patient.evolutions.build
end
def create
@evolution = @patient.evolutions.build(evolution_params)
if @evolution.save
redirect_to patients_url, notice: 'La evolucion fue agregada con exito'
else
render :new
end
end
def edit
end
private
def load_patient
@patient = Patient.find(params[:patient_id]
end
def evolution_params
params.require(:evolution).permit(:motivo, :evolution, :patient_id)
end
endhttps://stackoverflow.com/questions/68187121
复制相似问题