0
votes

Let's say I have a User model in rails with a date field called birth_date and an integer field called some_number. My problem is that if I do User.new(birth_date: "foo", some_number: "bar"), I will get no error. In fact I will get #<User id: nil, birth_date: nil, some_number: 0, created_at: nil, updated_at: nil>

I would like to have an error telling me that this field was not valid, so that the client can be warned. But since I do not necessarily need a birth_date then I cannot use a validation of birth_date with presence true. So the User end up being saved into the database with a birth_date equal to nil and no error.

The goal here is that if birth_date was sent in the params, then we will either save into the database with birth_date equal to nil BUT get an error message OR we don't save into the database at all. If birth_date was not sent in the params we don't throw an error.

I thought about a workaround that would look at the fields that were present in the params, look at what is indeed recorded into the database and compare the two. But I thought a nicer way probably exist.

For you to test, here is some code:

  • User model

    class User < ActiveRecord::Base

    end

  • User migration

class CreateUsers < ActiveRecord::Migration

  def change
    create_table :users do |t|
      t.date :birth_date
      t.integer :some_number

      t.timestamps null: false
    end
  end
end
  • User Controller

    class UsersController < ApplicationController def create user = User.new(birth_date: "foo", some_number: "bar") raise user.inspect end end

Thanks a lot for your help!

1
should the has_key method not fit your needs? You can then check with if params.has_key(:birth_date) then - theDrifter

1 Answers

1
votes

You probably want to create a custom validation (see here) that adds the desired message to the error array on the user instance. The guide walks through the salient bits.