arrays - 在 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() 这种方法是否足够好,还是有更正确的方法?谢谢你
解决方案
不要尝试在模型中验证这一点,而是验证表单条目。
为表单创建模型并使用常规验证。
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
推荐阅读
- python - Python 和 mailchimp 集成
- python - BigInteger 的 SQLAlchemy TypeDecorator 返回十进制?
- android - kotlin 数据存储
- python-3.x - AttributeError:模块“cv2.cv2”没有属性“CAP_PROP_ORIENTATION_META”
- python - 如何生成 Python 目录列表(树形结构)?
- python-3.x - 在 Python 中使用 Selenium 尝试识别特定按钮的编号,然后根据该编号单击所有该按钮
- go - Gorm 无缘无故返回已删除的值
- java - 为什么带有自定义 DateTimeFormatter 模式的 LocalDate 错误地设置了带区域的时间?
- javascript - 在页脚滚动上保持固定
- vba - TreeView1_NodeCheck 编译错误:过程声明与具有相同名称的事件或过程的描述不匹配