我已经通过关系表获得了处方与药物相关的模型应用程序。 我使用一个表格来创建一个包含5个关系的处方,其中包含有关medicine_id,amount,daily等的信息。然而,药物表有更多的信息,这就是我想在验证时使用的。
例如 - 我想检查来自表格dose
的字段medicines
是否类似于''%pills'。如果是这样,我想做一些计算来检查用户在填写表格期间放入的金额是否在范围内(假设30-40只适用于这种特定药物)
我的关系模型:
class Relation < ActiveRecord::Base
belongs_to :prescription
belongs_to :medicine
validates :amount, numericality: {only_integer: true, :greater_than_or_equal_to => 1 }
validates :daily, numericality: {only_integer: true, :greater_than_or_equal_to => 1 }
validates :period_in_days, numericality: {only_integer: true, :greater_than_or_equal_to => 1 }
validate :amount_limit, :if => :pills_form?
private
def amount_limit
end
def pills_form
end
end
当我验证关系时,如何获得药物表中的这些信息?或者还有其他更合适的方法吗?
答案 0 :(得分:0)
Aswer感谢@BroiSatse
class Relation < ActiveRecord::Base
belongs_to :prescription
belongs_to :medicine
validates :amount, numericality: {only_integer: true, :greater_than_or_equal_to => 1 }
validates :daily, numericality: {only_integer: true, :greater_than_or_equal_to => 1 }
validate :amount_limit, :if => :pills_form?
private
def amount_limit
max_amount = self.daily * 90
in_box_amount = medicine.cardinality.scan(/\d+/).first
sum = self.amount * in_box_amount.to_i
if sum > max_amount
errors.add(:amount, "An amount of medicine cannot exceed 90 days of treatment.")
end
end
def pills_form?
pill_form_array = ['plaster' , 'globul', 'czop', 'guma', 'tablet', 'pastyl', 'kaps', 'lamel']
pill_form_array.any? { |item| medicine.form =~ /#{item}/ }
end
end