创建时将值推送到模型 - Rails

Push value to model when created - Rails

如果用户是 current_clinician:

  def create
    esas_assessment_params = params.require(:esas_assessment).permit(:patient_id, :clinician_id, :time, :year, :month, :day, :inputter_name, :inputter_id, :pain, :pain_comment, :tiredness, :tiredness_comment, :drowsiness, :drowsiness_comment, :nausea, :nausea_comment, :lack_of_appetite, :lack_of_appetite_comment, :shortness_of_breath, :shortness_of_breath_comment, :depression, :depression_comment, :wellbeing, :wellbeing_comment, :other_symptom_id, :other_symptom_score, :other_symptom_comment, :esas_comment)
    @esas_assessment = EsasAssessment.new(esas_assessment_params)
    if current_clinician
      @esas_assessment.clinician = current_user.clinician
      @esas_assessment.inputter_name = current_user.clinician.full_name
      @esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')
    else
      @esas_assessment.patient = current_user.patient
      @esas_assessment.clinician = current_user.patient.clinician
    end
    if @esas_assessment.save
      redirect_to esas_assessments_path, notice: "ESAS assessment submitted!"
    else
      render "new", alert: "ESAS assessment not submitted!"
    end
  end

或更简单地说:

  def create
    esas_assessment_params = params.require(:esas_assessment).permit!
    @esas_assessment = EsasAssessment.new(esas_assessment_params)
     @esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')
    if @esas_assessment.save
      redirect_to esas_assessments_path, notice: "ESAS assessment submitted!"
    else
      render "new", alert: "ESAS assessment not submitted!"
    end
  end

在第一个示例中,将 @esas_assessment.clinician 值自动设置为 current_user.clinician 和设置 inputter_name 的行都有效,但 inputter_id 无效。

我的 EsasAssessment 模型是:

EsasAssessment:
  patient_id: integer
  clinician_id: integer
  created_at: datetime
  updated_at: datetime
  inputter_name: string
  inputter_id: integer

class EsasAssessment < ActiveRecord::Base
    belongs_to :other_symptom
    belongs_to :clinician
    belongs_to :patient
    belongs_to :inputter
end

输入者是:

Inputter:
  inputter_type: string

class Inputter < ActiveRecord::Base
    has_many :esas_assessments
end

当我提交表单时,我没有收到任何错误或警告,inputter_id 只是 nil

如果我输入

Inputter.find_by(inputter_type: 'Medical team')

在控制台中 returns

#<Inputter {"id"=>309, "inputter_type"=>"Medical team"}>

任何关于如何获得坚持新 EsasAssessment 的价值的建议都很棒

我猜你应该分配找到的输入器的 id,而不是这一行中的对象本身

@esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')

类似于

@esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team').try(:id)

或者

@esas_assessment.inputter = Inputter.find_by(inputter_type: 'Medical team')