mercredi 5 août 2015

Rails Active Record validates_precense_of not flashing error message

I have a text box in a rails application that I want to validate the pretense of an input before saving to the db. So, I tried placing a validates_precense_of callback in the correct model (as shown below).

class Suggestion < ActiveRecord::Base
  attr_accessible :details, :metadata, :suggestible, :user
  belongs_to :suggestable, polymorphic: true
  belongs_to :user
  serialize :metadata, JSON
  validates_presence_of :details
end

Instead of the request failing and flashing an error message, the request is successful, and no suggestion record is ever saved in the suggestions table.

I've debugged and confirmed (see controller below) @suggestion.details.blank? and .empty return true is the text box is empty.

Here's the controller action:

  def select_patients
    @rx_search_request = RxSearchRequest.find(params[:id])
    @groups = []
    params['selected_patient_group'].each do |id, selected|
      @groups << id if selected == "true"
    end

      unless @groups.blank?

        @rx_search_request.select_multiple_patient_group_ids(@groups)

        unless @rx_search_request.approval_status_reason_patients_and_approval? ||
          @rx_search_request.approval_status_reason_requires_approval?
          @rx_search_request.needs_consolidation!
          # @rx_search_request.approve! approved_by: current_user
          @redirect_url = rx_search_request_path(@rx_search_request)
          # @message = "Request has been created."
        else
          @message = "Request has been forwarded to your admin for approval."
        end

      end
    if params.keys.include? "suggestion"
      #we are submitting a suggestion
      group_ids = params[:selected_patient_group].collect{|k,v| k if v == 'true'}.compact
      metadata = {
        group_ids:group_ids,
        patient_ids:ManualConsolidationPatientGroup.find(group_ids).collect{|g| g.manual_consolidation_patients}.flatten.collect{|_p| _p.id}
      }

      @suggestion = @rx_search_request.suggestions.new({
        details:params[:suggestion_box],
        metadata: metadata
      })
      @suggestion.user = current_user
      @suggestion.save
      # @message = "Your suggestion has been submitted."
      # debugger
      # flash[:alert] = 'Your suggestion cannot be blank' if @suggestion.details.empty?
      flash[:alert] = 'Your suggestion has been submitted.'
    end

    respond_to do |format|
      format.js
    end
  end

Aucun commentaire:

Enregistrer un commentaire