Reputation: 4629
I have a HABTM relationship between Products and Categories. Those Categories belongs to a user.
At my product form, I only show checkboxes for the current user. But i want to validate this on model too, so users can't fake POST variables and assign it to invalid categories.
How can i do such validation?
Example: given a category_id 5, i have to check if this category belongs to current_user.id ( provided by devise ).
Thanks.
Upvotes: 2
Views: 778
Reputation: 1373
You can add attr_accessor: creator_id
to your Post
model. (creator_id
is not in database )
And send current_user.id
from form to Post
's creator_id
.
Then use model callbacks. For example after_validation
:
after_validation do
if User.find(creator_id).categories.pluck(:id).include?(category_id)
true
else
errors.add :category, "is invalid for user"
end
end
Upvotes: 1