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または、ブロック内にあるにもかかわらず、エラー メッセージを 1 回だけ表示する方法はありますか。

PS: ネストされた属性 (アイテム) に cocoon を使用しています

ありがとう。任意の回避策をいただければ幸いです。

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 に答える