I’m working on a Rails 7 application with the following models and associations.
For example, there are models and associations:
class Article < ApplicationRecord
has_many :article_classifiers
has_many :classifiers, through: :article_classifiers
end
class Classifier < ApplicationRecord
has_many :article_classifiers
has_many :article, through: :article_classifiers
end
class ArticleClassifier < ApplicationRecord
belongs_to :article
belongs_to :classifier
end
I need to validate the existence of Classifier objects before creating or updating an Article. In the controller, I receive a classifier_ids parameter, which is an array of IDs intended for association with the article. There’s a possibility that one or more of these classifiers may have been deleted, necessitating a check before updating.
Rails automatically adds Article.classifier_ids and Article.classifier_ids= methods with such associations. Here’s how I’ve customized these methods along with adding an accessor and custom validation:
attr_accessor :temp_classifier_ids
def classifier_ids
classifiers.pluck(:id)
end
# Here we automatically get ids from the request parameters of the controller
def classifier_ids=(ids)
ids = ids.compact_blank.map(&:to_i)
self.temp_classifier_ids = ids
self.classifiers = Classifier.where(id: ids)
end
validate :check_classifiers_existence
def check_classifiers_existence
return if Classifier.classifiers_exist?(temp_classifier_ids)
errors.add(:base, 'Classifier not exist')
end
This setup works, but I’m not certain it’s the most Rails-idiomatic approach. What would be the best practice for validating the existence of associated classifiers before saving in Rails?
georgyVS is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.