Reputation: 1763
I have a Product model which belongs_to a Category. A User only has access to a few categories.
How do I validate when creating a Product, that the User has access to the category_id
it is trying to assign?
Let's assume I have the list of allowed Categories in session[:category_ids]
.
In the controller I use strong parameters like so:
def product_params
params.require(:product).permit(:name, :description, :category_id)
end
Is it possible to filter out values we dont have access to here? Or is there a better way to achieve this?
Upvotes: 1
Views: 504
Reputation: 2051
In your products_controller add
before_action :require_category_access
in your Product model create some function that checks to see if the user has access to the correct categories which will run before the data is saved.
def require_category_access
if current_user <has access to the category>
return true
else
redirect_to some_url
flash[:error] = "no access for you"
end
end
Upvotes: 1