vendredi 28 avril 2023

How to validate an updated has-many-through collection

I am try to figure out how to properly validate a model collection whenever that collection is updated using the << collection operator. In our legacy app (Rails 3.2.1), I found that platform_collection_obj.platforms is updated using << operator

Example:

collection.platforms << new_platform

In researching how to validate that each platform in platforms collection has appropriate data, I found that I should use custom-validation function. So I tried adding each_platform_branch_id validation function to PlatformCollections Model. However, I found in testing (via rails console) that the validation was not triggered.

In reading Has-Many-Association-Collection Info, I came across this

Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record. This will also run validations and callbacks of associated object(s).

This excerpt indicates that using << to perform update on collection.platforms will not trigger the parent validations, which in this case would be the PlatformCollection:each_platform_branch_id validation function. I know that manually perforning collection.save would trigger validation, but it would be too late b/c << has already updated the DB.

So to restate the question is: How do I properly validate a has-many-through-model collection whenever that collection is updated using the << collection operator?

PlatformCollections Model

class PlatformCollection < ActiveRecord::Base
  belongs_to :tezt
  has_many :platform_collection_platforms, :order => "platform_collection_platforms.default DESC"
  has_many :platforms, :through => :platform_collection_platforms, :order => "platform_collection_platforms.default DESC"

  def each_platform_branch_id
    platforms.each do |p|
      if p.branch_id != @branch.id
        err_msg = "Invalid Platform: #{p.to_json} for PlatformCollection: #{self.to_json}. " \
                  "Expected Branch: #{@branch.id}, Actual Branch: #{p.branch_id}"
        errors.add(:platform, err_msg)
      end
    end
  end

Platforms Model

class Platform < ActiveRecord::Base
  attr_accessible :name
  belongs_to :branch
  has_many :platform_collection_platforms
  has_many :platform_collections, :through => :platform_collection_platforms

Aucun commentaire:

Enregistrer un commentaire