Rails 4 custom validation with many-to-many relati

2019-08-21 08:31发布

问题:

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.

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)

My relation model:

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?

回答1:

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