bootstrap_form icon indicating copy to clipboard operation
bootstrap_form copied to clipboard

Validating with belongs_to required: true

Open matthttam opened this issue 8 years ago • 2 comments

I know the documentation currently states:

The label required class is determined based on the definition of a presence validator with the associated model attribute. Presently this is one of: ActiveRecord::Validations::PresenceValidator or ActiveModel::Validations::PresenceValidator.

It would be wonderful if the belongs_to required: true validation would work instead. rails-bootstrap-forms shows the error in the top box but doesn't apply the has-error class to the group or add a message under the field. This seems to be because the name (or maybe id) isn't for the ID version of the field.

Example:

class Person < ActiveRecord::Base belongs_to :location, required: true end

This model validation when failed will not apply has-error to the group. The field name ends up being person[location] instead of person[location_id] which is the actual field name.

The workaround is to not use "required: true" and instead use: validates :location_id, presence: true

It would be wonderful if the required: true validation was used properly to add classes.

matthttam avatar Mar 25 '16 21:03 matthttam

Hey @matthttam, it has been a while since I looked at this but seems like Rails 5 is going to make this even more relevant is it apparently makes belongs_to default to required (http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html).

I actually didn't know about the required: true option and have always used validators. Either not common or people have been just dealing with this for a while.

I'll take a stab at this although seems like there is a bit of a backlog with PRs ...

krsyoung avatar May 27 '16 01:05 krsyoung

So, turns out this is a little tricky. The required: true option was added in rails 4.2.0 (http://raysrashmi.com/2014/09/02/new-features-in-rails-4-2/) and the sample (dummy) project included with this project is rails 4. This makes testing the thing a little difficult.

I have code working locally (rails 4.2.6) and passing test cases but I'm not sure the best path forward with respect to testing. I also have a feeling it might be very fragile. At a minimum maybe @matthttam maybe you could give my branch and try and validate that it works for you?

https://github.com/krsyoung/rails-bootstrap-forms/tree/support-belongs_to-required

krsyoung avatar May 28 '16 03:05 krsyoung

This has been implemented recently.

donv avatar Sep 08 '23 13:09 donv