ruby 如何验证更新的has-many-through集合

7z5jn7bk  于 2023-04-29  发布在  Ruby
关注(0)|答案(1)|浏览(78)

我试图弄清楚如何正确地验证一个模型集合,每当该集合使用〈〈集合操作符更新时。在我们的遗留应用程序(Rails 3.2.1),我发现platform_collection_obj.使用〈〈运算符更新平台

示例

collection.platforms << new_platform

在研究如何验证平台集合中的每个平台都有合适的数据时,我发现应该使用custom-validation函数。所以我尝试在PlatformCollectionsModel中添加each_platform_分支_id验证函数。然而,我在测试中(通过Rails控制台)发现验证没有被触发。
在阅读Has-Many-Association-Collection Info时,我遇到了这个问题
通过将一个或多个对象的外键设置为集合的主键,将这些对象添加到集合中。请注意,除非父对象是一条新记录,否则此操作会立即触发更新SQL,而不等待父对象上的保存或update调用。这还将运行相关对象的验证和回调。
此摘录表明使用
〈〈对集合执行更新。platformCollection:each_platform_分支_id验证函数。我知道手动执行收集。保存将触发验证,但为时已晚b/c**〈〈**已更新DB。
所以我想重申一下问题是:当使用〈〈集合操作符更新一个has-many-through-model集合时,如何正确地验证该集合?

PlatformCollections模型

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

平台型号

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

uqcuzwp81#

这里根本不用<<操作符(collection.platforms << new_platform),也许最好显式创建JOIN记录?
例如:

collection.platform_collection_platforms.build(
  platform_collection: collection,
  platform: new_platform
)

(My天哪,这是一组令人困惑的名字!!)
现在你可以完全控制validate

相关问题