Ruby on rails 在Rails 3.2中的DO块内显示一次错误消息
嗨,我有两个相互关联的模型: 项目采购管理计划Ruby on rails 在Rails 3.2中的DO块内显示一次错误消息,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,嗨,我有两个相互关联的模型: 项目采购管理计划有很多:项目 项目属于:项目・采购・管理・计划 项目采购管理计划.rb: class ProjectProcurementManagementPlan < ActiveRecord::Base attr_accessible :attachment, :agency_id, :user_id, :year, :status, :code, :prepared_by, :submitted_by, :it
有很多:项目
项目属于:项目・采购・管理・计划
项目采购管理计划.rb
:
class ProjectProcurementManagementPlan < ActiveRecord::Base
attr_accessible :attachment, :agency_id, :user_id, :year, :status, :code, :prepared_by,
:submitted_by, :items_attributes, :pmo_end_user, :attachments_attributes,
:category_id, :combine_in_app, :mode_of_procurement_id, :contract_type_id,
:estimated_budget, :created_at, :updated_at, :currency
has_many :items, dependent: :destroy, :order=>"created_at ASC"
accepts_nested_attributes_for :items, :reject_if => lambda { |a| a[:category_id].blank? },
:allow_destroy => true
validate :equality, :reduce=>true
def equality
self.items.each do |item|
errors.add(:base, "Quantity must be equal to the breakdown of quantity!") if item.months != item.qty
end
end
end
因为我将动作从项传递到另一个模型,所以我使用的是self
。验证在项目采购管理计划文件中。我还知道,第一个模型的相等
方法中的每个do
块是我有多个/冗余错误显示消息的原因。是否有任何方法可以在不使用每个do块的情况下将动作从一个模型传递到另一个模型
我试过:
def equality
item = self.items
errors.add(:base, "Quantity must be equal to the breakdown of quantity!") if item.months != item.qty
end
但是没有运气。它说未定义的方法“月”
。或者,是否有任何方法只显示一次错误消息,尽管它位于每个do
块中
PS:我将cocoon用于嵌套属性(项目)
谢谢。任何解决方法都将不胜感激。要显示一次错误消息,您可以尝试:
def equality
self.items.each do |item|
unless errors.find.include?("Quantity must be equal to the breakdown of quantity!")
{
errors.add(:base, "Quantity must be equal to the breakdown of quantity!") if item.months != item.qty && errors.!include?
break
}
end
end
您应该验证
Item
模型本身中的项目,它将帮助您了解哪些项目存在验证错误。但是,如果您只想将错误与ProjectProcurementManagementPlan
关联,可以这样做:
def equality
self.items.each do |item|
if item.months != item.qty
errors.add(:base, "Quantity must be equal to the breakdown of quantity!")
return
end
end
end
如果第一项有准确的值,但第二项或第三项没有。什么是
错误。!是否包括?
?还有一件事,这样你就必须迭代每个项目。如果有10个项目,第二个项目的数量不正确,那么为什么要循环其他8个项目,当发现第一个数量不正确/错误时,应该打破循环。看看我的答案。
def equality
self.items.each do |item|
if item.months != item.qty
errors.add(:base, "Quantity must be equal to the breakdown of quantity!")
return
end
end
end