嗨,我有 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:我将茧用于嵌套属性(项目)
谢谢。任何解决方法将不胜感激。