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?
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
unless instead of if followed by !. So in this case, unless languages.kind_of?(Array).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: [])
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
add_column :users, :languages, :string, array: true, default: [], strong parameters:params.require(:user).permit(:email, :password, :password_confirmation, languages: [])