I have method called check_field, purpose of this method is for checking is there multiple value when input form.
I was think maybe I can check with multiple array on rails. I found some code on this link to check duplicate value inside array. So, I implement that method (difference
) on my model
, but I got stuck when implement to my Model, the methot won't called.
NoMethodError (undefined method `difference' for ["vvvv", "vvvv", "xxxxxxxxx", "xxxxxxxxx"]:Array):
here my Code.
class Model < ApplicationRecord
has_many :child_models, -> { where(active: true) }, :foreign_key => :model_id, :dependent => :destroy
accepts_nested_attributes_for :child_models, :allow_destroy => false
before_validation :check_field, :before => [:create]
def check_field
all_field = Array.new
child_models.each do |data|
all_field << data.field
end
uniq_field = all_field.uniq
result = uniq_field - all_field.difference(uniq_field)
errors.add(:field, "Field must be Different")
end
def difference(other)
h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
reject { |e| h[e] > 0 && h[e] -= 1 }
end
end
the field that I want to validate is on child_models,
class ChildModel < ApplicationRecord
validates :field, presence: { message: "Field" + I18n.t("sys_err_is_required"), :if => :active?, :scope => [:active] }, :uniqueness => { :message => 'Field is already exist', :if => :active?, :scope => [:active], :case_sensitive => false }
end
I was try to put check_field
method on ChildModel, it didn't work, because the parameters can be read on Model class.
so then any solution for this case? thanks.