Rails 4自定义验证与多对多关系

时间:2014-05-27 18:22:57

标签: ruby validation ruby-on-rails-4 many-to-many

我已经通过关系表获得了处方与药物相关的模型应用程序。 我使用一个表格来创建一个包含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

当我验证关系时,如何获得药物表中的这些信息?或者还有其他更合适的方法吗?

1 个答案:

答案 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