您好我有两个相互关联的模型:
ProjectProcurementManagementPlan has_many: items
项目 belongs_to :project_procurement_management_plan
project_procurement_management_plan.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
item.rb
:
class Item < ActiveRecord::Base
attr_accessible :code, :description, :estimated_budget,
:project_procurement_management_plan_id, :quantity, :unit, :category_id,
:combine_in_app, :mode_of_procurement_id, :contract_type_id, :january,
:february, :march, :april, :may, :june, :july, :august, :september, :october,
:november, :december
belongs_to :project_procurement_management_plan
def months
total = january + february + march + april + may + june + july + august +
september + october + november + december
end
def qty
self.quantity
end
end
由于我将操作从项目传递到其他模型,因此我使用self
。验证在项目采购管理计划文件中。我也知道第一个模型的each do
方法中的equality
块是我有多个/冗余错误显示消息的原因。有没有办法在不使用each do
块的情况下将操作从模型传递到模型?
我试过了:
def equality
item = self.items
errors.add(:base, "Quantity must be equal to the breakdown of quantity!") if item.months != item.qty
end
但没有运气。它说undefined method 'months'
。或者有没有办法只显示一次错误消息,尽管它位于each do
块内。
PS:我使用cocoon作为嵌套属性(项目)
感谢。任何变通办法都将受到赞赏。
答案 0 :(得分:0)
您应该验证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
答案 1 :(得分:-1)
对于显示错误消息一次,您可以尝试:
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