0

嗨,我有 2 个相互关联的模型:

项目采购管理计划 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

由于我将动作从 item 传递到另一个模型,所以我使用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:我将茧用于嵌套属性(项目)

谢谢。任何解决方法将不胜感激。

4

2 回答 2

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
于 2013-02-22T06:14:57.920 回答
-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
于 2013-02-22T05:57:39.297 回答