mardi 5 mai 2015

Push value to model when created - Rails

I am trying to set the inputter_id value automatically to the id for for the inputter_type corresponding to "Medical team" in a form if the user is a 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

or more simply:

  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

in the first example the lines to set the @esas_assessment.clinician value automatically to the current_user.clinician and setting the inputter_name both work but the inputter_id doesn't.

My EsasAssessment model is:

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 is:

Inputter:
  inputter_type: string

class Inputter < ActiveRecord::Base
    has_many :esas_assessments
end

When I submit my form I don't get any errors or warning, inputter_id is just nil

if I enter

Inputter.find_by(inputter_type: 'Medical team')

in Console it returns

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

Any advice on how to get the value to stick to the new EsasAssessment would be great

Aucun commentaire:

Enregistrer un commentaire