My app is a social platform and I want to have the support-team being able to maintain a blacklist for nicknames. Therefore I have a model Blacklist that contains the different names.
Now I tried with the validates_exclusion_of
to map these into the in:
but it raises the following error,
wrong number of arguments (given 1, expected 0)
validates_exclusion_of :nickname, in: -> {
where(Blacklist.select(:name).map(&:name).uniq.to_s)
}, message: "This nickname is not allowed"
You don't need to wrap the values to exclude within a lambda, it'll work as is if you pass just the Blacklist AR query result.
validates_exclusion_of :nickname,
in: Blacklist.select(:name).map(&:name).uniq.to_s,
message: 'This nickname is not allowed'
Notice, you can use the ActiveRecord::Calculations#pluck in order to get just the names from Blacklist, getting rid of the select and map combination, and use ActiveRecord::QueryMethod#distinct to get non-repeated values.
With that you don't need the uniq
and to_s
step. The last one, because the validation is waiting for an enumerable object, and you'd be passing a string.
Something like:
validates_exclusion_of :nickname,
in: Blacklist.distinct.pluck(:name),
message: 'This nickname is not allowed'
The where
you're using on the validation won't work, as it's applying a WHERE statement without passing a column name to check, so you'll get an ActiveRecord::StatementInvalid
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.