Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 验证Rails中的数组插入_Arrays_Ruby On Rails - Fatal编程技术网

Arrays 验证Rails中的数组插入

Arrays 验证Rails中的数组插入,arrays,ruby-on-rails,Arrays,Ruby On Rails,表1的属性attribute1是一个整数数组。我的控制器允许一次插入一个。因此,在控制器中: 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 def添加属性1

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

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
def添加属性1\u项
table1=table1.find(参数[:id])
表1.attribute1{attribute1.present?}
.
.
.
def属性1_项_有效
#通过访问attribute1验证该项
结束
我不确定这种方法,因为当我访问attribute1\u item\u中的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
class某种形式
包括ActiveModel::Model
属性访问器:id,:attribute1\u项
验证:id,存在性:true,数值性:{only_integer:true}
验证:属性1\u项,存在性:true
结束
def添加_属性1_项
form=SomeForm.new(参数)
如果表单无效?
#呈现形式错误
返回
结束
table1=table1.find(form.id)

表1.attribute1如果使用Rails 5.1+则使用
attribute:id、:integer
attribute:attribute1\u项
而不是
attr\u访问器
。attributes api将创建与ActiveRecord属性行为非常相似的属性,以便您可以在模型上调用
.attributes
,或对其进行序列化。
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