具有多对多关系的Rails 4自定义验证 [英] Rails 4 custom validation with many-to-many relationship
问题描述
我有一个带有模型的应用程序,其中处方通过关系表与药品联系在一起.我使用一种形式创建具有5种关系的一张处方,其中包含有关medicine_id,金额,每日等信息.但是,药表有很多信息,这就是我想在验证时使用的信息.
I've got app with model where prescriptions are connected with medicines via relations table. I use one form to create one prescription with 5 relations which contains information about medicine_id, amount, daily and so on. However, medicine table has got a lot more information and thats what I would like to use when validating.
例如-我想检查表 medicines
中的字段 dose
是否类似于''%pills'.如果是这样,我想做一些计算来检查用户在填写表格时输入的量是否在范围内(假设30-40只对这种特定药物正确)
For example - I want to check if field dose
from table medicines
is like `'%pills'. If so, I would like to do some calculation to check if an amount that user put during filling the form is in range (lets say 30-40 is only correct for this specific medicine)
我的关系模型:
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
我在验证关系时如何获得药物表中的这些信息?还是有其他更合适的方式做到这一点?
How can I get these informations that are in the medicine table when Im validating relations? Or is there any other, more proper way of doing this?
推荐答案
感谢@BroiSatse
Aswer thanks to the @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
这篇关于具有多对多关系的Rails 4自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!