Rails 4 custom validation with many-to-many relationship

情到浓时终转凉″ 提交于 2019-12-25 02:47:12

问题


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


来源:https://stackoverflow.com/questions/23896389/rails-4-custom-validation-with-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!