Ruby on Rails中同时具有多个表的数据验证应该在哪里进行?

时间:2019-07-13 10:55:28

标签: ruby-on-rails validation model-view-controller

我正在使用RoR,并且被如何正确,优雅地验证前端数据所困扰。我的服务器只是一个基于API的RoR应用。

有4个与此问题相关的表, identity_types 用于存储身份类型, identities 用于存储用户身份, users 用于存储密码摘要和其他信息,级别用于存储用户级别,例如工作人员,经理等。

为了简洁起见,我在YAML中使用伪代码来描述它们,并省略了常见字段,例如id,create_at等。

identity_types:
  name:             [string,  unique]
# e.g., name = email/telephone/nickname and etc.

identities:
  content:          [string,  unique]
  user_id:          [integer, not_null]
  identity_type_id: [integer, not_null]
# with combined unique contraint for [user_id, identity_type_id]

users:
  password_digest:  [string]
  supervisor_id:    [integer, not_null]
  level_id:         [integer, not_null]
  banned:           [boolean]

levels:
  name:             [string,  unique]
# e.g., name = worker/manager/director and etc.

分别,我在ActiveRecord中有它们的模型,相关的迁移以及它们的控制器。我遵守RESTful的规则,并将“ POST / users”定向到“ users#create”。

现在,这里出现一个问题:创建一个具有以下角色的新工作人员。

  1. 工人的主管只能是经理。
  2. 身份的内容不能重复。

我目前要做的是在控制器中而不是模型中加入很多逻辑。

# controllers/users_controller.rb
class UsersController < ApplicationController

  # params_from_fe = %i[identity_content identity_type_uuid password password_confirmation supervisor_uuid]

  def create
    # 1. check if required parameters are presented
    # 2. find_by identity_content and check if content is duplicated
    # 3. find_by supervisor_uuid and check if supervisor.level is manager
    # 4. Nothing done with password + password_confirmation, since they are processed by model layer.
    # if all checks passed:
      # user = User.create
      # user.identity.create
    # other code ...
  end
end

在上面的检查操作中,我对于身份内容具有唯一的约束,因此第二步可能被忽略了。 验证超级viosr是否为模型层管理者ActiveRecord的第三步怎么办?

谢谢。

0 个答案:

没有答案