【问题标题】:Writing logics other than validation inside validator method - rails 5在验证器方法中编写验证以外的逻辑 - rails 5
【发布时间】:2019-03-05 11:26:00
【问题描述】:

我有一个场景,我需要将关联记录的名称保存在当前对象中。

假设我有一个 JSON 列,并且我在该 JSON 列中有另一个表的 id。

例如请求:

users: {
  name: 'test', 
  additional_details: { another_table_id: 1}
}

我要做的是验证另一个表是否具有该 id(请求)。

所以我在用户模型中添加了自定义关联,

 validates :validate_additional_table


 def validate_additional_table
    a_t = AnotherTable.where(id: additional_details['another_table_id']).first

    if a_t.present?
      additional_details.merge!(another_table_record_name: a_t.name) # Is it a good practice?
    else
      errors.add(:base, 'record is invalid')
    end

 end

我添加了一些其他逻辑(检查上述验证器中的注释)。除了验证器中的验证逻辑之外,这是最佳实践吗?

【问题讨论】:

  • 我会说不。验证应该只是验证。如果您想保留其他附加信息,还有其他挂钩,例如 [before/after/around]_XXX

标签: ruby-on-rails activerecord ruby-on-rails-5 customvalidator


【解决方案1】:

我不知道在验证中做逻辑,但是使用

 AnotherTable.exists?(id: additional_details['another_table_id'])

而不是

a_t = AnotherTable.where(id: additional_details['another_table_id']).first

if a_t.present?
  additional_details.merge!(another_table_record_name: a_t.name) # Is it a good practice?

这只会获取数据库中存在的记录数,而不是将所有数据加载到内存中。并在保存回调后添加另一个表的名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多