Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor allow_blank escape hatch to work better with params. #956

Merged
merged 2 commits into from
Aug 5, 2023

Conversation

jwoertink
Copy link
Member

Fixes #954

We originally had an escape hatch that would allow you to store an empty string (blank value) on a String type that wasn't nilable. Normally this would be treated as nil, but there may be cases where you still want to allow the empty string value while avoiding a nilable type.

The issue though was it only worked when you passed the value by named arg, and it required shutting off ALL required validations. This meant that if you had another string value that you didn't want to be blank, it could still potentially sneak in.

This PR moves the logic to the column field itself with a new allow_blank: true option. Now you no longer need to add skip_default_validations so all of your other required types can still get their validations. It also fixes working with params that you pass in. If you do happen to pass a nil value, you'll just get a runtime PG exception instead.

class Preference < BaseModel
  table do
    column color : String, allow_blank: true
  end
end

# {"preference": {"color": ""}}
SavePreference.create(params) do |op, pref|
  op.valid? == true
end

SavePreference.create(color: "") do |op, pref|
  op.valid? == true
end

Copy link
Contributor

@robacarp robacarp left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's some weird nuance here. As a database API, I absolutely expect it to know the difference between a '' and a nil, and to not infer between the two.

Unfortunately HTTP params aren't similarly equipped to handle that nuance. The best it has is to say that if the parameter is absent (or undefined), it is nil. Whereas if it is present it can be blank and must be validated as a string, based off of it's contents.

I guess what I'm saying is, nil-able-ness is something that has to be handled at one layer. String composition, including if it is blank or not, feels like maybe it should be handled at another.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Setting allow_blank on attributes may not work from params
2 participants