こんにちは、互いに関連する 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 を使用しています
ありがとう。任意の回避策をいただければ幸いです。