Get errors when creating associations

I have this validation in my app_setting model:

    class AppSetting < ActiveRecord::Base
      belongs_to :event
      validates :id_monitoring_system, numericality: { only_integer: true }, allow_blank: true
    end

I have a controller where I create events:

  def create
    @event = Event.new(event_params)

    unless params[:app_setting].nil?
      app_setting = JSON.parse(params[:app_setting])
      @event.build_app_setting(app_setting)
    end

    if @event.save
      render json: {status: 'created', message: 'Event save'}
    else
      render json: {status: false, errors: @event.errors.full_messages}
    end
  end

I want to get the app_setting validation errors by the id_monitoring_system attribute and show them in my view

when the attribute is not an integer the association is not created and does not show me the errors

I tried:

    begin
      unless params[:app_setting].nil?
        app_setting = JSON.parse(params[:app_setting])
        @event.create_app_setting!(app_setting)
      end
    rescue ActiveRecord::RecordInvalid => e
      errors.add(:base, 'id_monitoring_system is integer')
    end

But that doesn't work, how could I solve it?

Upvotes: 2

Views: 150

Answers (1)

R. Sierra
R. Sierra

Reputation: 1204

The validation is defined in AppSetting so it will add the errors to the class instance. Try this on the rails console:

s = AppSetting.new(id_monitoring_system: 'foo')
s.valid?
 => false
s.errors.full_messages # should output something like
 => ['id_monitoring_system must be an integer'

Depending on how you defined the association between Event and AppSetting in the Event class it may trigger a validation error. I would expect to have the association defined like so:

class Event < ActiveRecord::Base
  has_one :app_setting, required: true

That way when doing:

@event.build_app_setting(id_monitoring_system: 'foo')
@event.save

It will cause AppSetting to fail the numericality validation and in turn Event will fail cause the association is required. But the error shown in @event will be can't be blank. To show the AppSetting validation error, you should add it to the parent class errors instance

if @event.save
  render json: {status: 'created', message: 'Event save'}
else
  @event.errors.add(:base, @event.app_setting.errors.full_messages)
  render json: {status: false, errors: @event.errors.full_messages}
end

Upvotes: 1

Related Questions