Take the 2-minute tour ×

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 ).


share|improve this question

1 Answer 1

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)
    errors.add :category, "is invalid for user"
share|improve this answer

Your Answer


