首页 > 解决方案 > 在 Rails 中验证数组插入

问题描述

我有带有属性attribute1 的Table1,它是一个整数数组。我的控制器允许一次插入一个。因此,在控制器中:

def add_attribute1_item
  table1 = Table1.find(params[:id])
  table1.attribute1 << add_params[:attribute1_item]
  table1.save!
  render json: table1
rescue
  render_errors_for(table1)
end

我想验证这个attribute1_item值,忽略已经存储在attribute1数组中的旧值,例如如果table1.attribute1包含99并且我调用控制器add_attribute1_item添加100,我只想检查100是否有效,忽略99.

class Task < ApplicationRecord
     .
     .
     .
  validate :attribute1_item_is_valid, if: -> { attribute1.present? }
     .
     .
     .
  def attribute1_item_is_valid
    # validate the item by accessing attribute1
  end

我不确定这种方法,因为当我访问attribute1_item_is_valid 中的attribute1 时,它是整个数组而不是新项目。通过调用 attribute1.last() 这种方法是否足够好,还是有更正确的方法?谢谢你

标签: arraysruby-on-rails

解决方案


不要尝试在模型中验证这一点,而是验证表单条目。

为表单创建模型并使用常规验证。

class SomeForm
  include ActiveModel::Model

  attr_accessor :id, :attribute1_item

  validate :id, presence: true, numericality: { only_integer: true }
  validate :attribute1_item, presence: true
end

def add_attribute1_item
  form = SomeForm.new(params)
  if form.invalid?
    # render form.errors
    return
  end

  table1 = Table1.find(form.id)
  table1.attribute1 << form.attribute1_item
  table1.save!
  render json: table1
rescue
  render_errors_for(table1)
end

推荐阅读