0

I have attribute user`s languages. When form submit, it must return array?

I want to write validation in model User:

validates :languages, presence: true

How write in validates, returning value must be is array?

2
  • Are you saving this field? How is languages defined in the database? Commented Feb 7, 2018 at 2:23
  • 1
    in migration add_column :users, :languages, :string, array: true, default: [], strong parameters: params.require(:user).permit(:email, :password, :password_confirmation, languages: []) Commented Feb 7, 2018 at 2:36

3 Answers 3

3
class User< ApplicationRecord
  validate :languages_is_array

  def languages_is_array
    if !languages.kind_of?(Array)
      errors.add(:languages, "must be an array")
    end
  end

  #Another version, as moveson commented
  def languages_is_array
    errors.add(:languages, "must be an array") unless languages.kind_of?(Array)
  end

end
Sign up to request clarification or add additional context in comments.

1 Comment

Ruby idiom is to use unless instead of if followed by !. So in this case, unless languages.kind_of?(Array).
0

You can declare that a param needs to be an array in you controller if you are concerned about what the user submits in the form and not so much the validation of the model.

See: Action Controller Overview - 4.5 Strong Parameters

To declare that the value in params must be an array of permitted scalar values, map the key to an empty array:

params.permit(id: [])

Comments

0

You can also create your own custom validator for attributes.

In this case it could look like:

class ArrayValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value.is_a? Array
      record.errors.add attribute, (options[:message] || "must be an array")
    end
  end
end

class User < ApplicationRecord
  validates :languages, array: true
end

See: https://guides.rubyonrails.org/active_record_validations.html#custom-validators

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.