2

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.

4

1 回答 1

1

您可以添加attr_accessor: creator_id到您的Post模型中。(creator_id不在数据库中)

current_user.id从表单发送到Post's creator_id

然后使用模型回调。例如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
于 2012-05-01T17:21:24.767 回答