Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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
Ruby on rails 4 如何将错误添加到Rails 4的嵌套模型中,在字段\u中可以看到,该字段包含\u errors div和errors数组_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 4 如何将错误添加到Rails 4的嵌套模型中,在字段\u中可以看到,该字段包含\u errors div和errors数组

Ruby on rails 4 如何将错误添加到Rails 4的嵌套模型中,在字段\u中可以看到,该字段包含\u errors div和errors数组,ruby-on-rails-4,Ruby On Rails 4,我有一个模型费用与费用细节有很多关系。 在费用模型中,我进行控制,并向费用及其嵌套属性添加错误 错误是需要添加两次错误: -要创建的一个将显示带有错误div的字段 -另一个用于通过实例变量显示错误 class Expense < ActiveRecord::Base has_many :expense_details, dependent: :destroy accepts_nested_attributes_for :expense_details, :allow_destroy

我有一个模型费用与费用细节有很多关系。 在费用模型中,我进行控制,并向费用及其嵌套属性添加错误

错误是需要添加两次错误:

-要创建的一个将显示带有错误div的字段

-另一个用于通过实例变量显示错误

class Expense < ActiveRecord::Base
 has_many :expense_details, dependent: :destroy
 accepts_nested_attributes_for :expense_details,  :allow_destroy => :true
 validate :control_teletrabajo

 def control_teletrabajo
   expense_details.each do |expense_detail|
   if control_fails
      # first:
      errors["expense_details.expense_month"] << "error message")
      # second: 
      expense_detail.errors.add(:expense_month) 
   end
 end
但是这句话没有将错误添加到@expense实例变量的errors数组中:@expense.errors,因此不会显示。这句话生成了“带错误的字段”div


另一个
errors[“expense\u details.expense\u month”]您提到
:teletrabajo\u repetido
是自动翻译的,但为了排除您的区域设置文件或翻译过程中的任何问题,如果您只使用字符串,例如
expense\u detail.errors.add(:expense\u month,'test error string')
。也许我没有解释清楚,在第一段代码中,我是否输入expense\u detail.errors.add(:expense\u month,“string error”)或expense\u detail.errors.add(:expense\u month,:msg\u error):在@expense save之后,它不会将错误添加到errors数组中(@expense.error不包含expense\u month错误)我对问题进行了编辑,使其更具可读性。现在请看一看。谢谢您可以尝试验证与您相关的。好的,解决方案是充分利用验证,
使用反向的
验证相关的
,这似乎是没有必要的(如果我这样说的话,嵌套模型验证了两次……我还在研究这一点)。同时,将嵌套模型验证放在适当的位置
 expense_detail.errors.add(:expense_month,"error message")