在验证器方法中编写除验证之外的逻辑 - rails 5

问题描述 投票:0回答:1

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

考虑一下我有一个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

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

ruby-on-rails activerecord ruby-on-rails-5 customvalidator
1个回答
0
投票

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

 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?

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

© www.soinside.com 2019 - 2024. All rights reserved.