I use acts-as-taggable-on gem to populate a user interests on a User model like this
# User.rb
acts_as_taggable
acts_as_taggable_on :interests
As I populate the interest_list array, I need to check that the given values matches against a constant array to make sure these are accepted values, something like this
VALID_INTERESTS = ["music","biking","hike"]
validates :interest_list, :inclusion => { :in => VALID_INTERESTS, :message => "%{value} is not a valid interest" }
The code above returns the following error
@user = User.new
@user.interest_list = ["music","biking"]
@user.save
=> false …. @messages={:interest_list=>["music, biking is not a valid interest"]}
I can see the inclusion doesn’t realize it should iterate over the array elements instead of s considering as a plain string but I’m not sure how to achieve this. Any idea?
The standard inclusion validator will not work for this use case, since it checks that the attribute in question is a member of a given array. What you want is to check that every element of an array (the attribute) is a member of a given array.
To do this you could create a custom validator, something like this:
I’m getting the elements of
interest_listnot inVALID_INTERESTSby taking the difference of these two arrays.I haven’t actually tried this code so can’t guarantee it will work, but the solution I think will look something like this.