Search code examples
ruby-on-railsrubygemsclient-side-validation

Rails 6 gem client_side_validations applied to a model with context not working


I have a model like this:

class Profile < ApplicationRecord
  validates :username, presence: true, on: :data_setup
end

where :data_setup is a page.

After installing the client side validation gem, it won't work, unless I erase the context part on: :data_setup

Is there any way to make it work?


Solution

  • Your expectations for this are completely wrong. Models are not aware of the request, controller or anything else really outside the the model unless you explicitly pass it in or its a global.

    For validations on: is most commonly used to restrict the validation to the create or update contexts. Note that this has nothing to do with what "page" you are on - the context is just tied to if the model instance is a new record or not.

    When using custom contexts you need to manually trigger it by passing the context to valid?, invalid? or save:

    Profile.new(username: nil).valid? # true
    Profile.new(username: nil).valid?(:data_setup) # false