gpt4 book ai didi

ruby-on-rails - 使用 :reject_if => :all_blank on double nested forms

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:26 24 4
gpt4 key购买 nike

所以我有以下模型

宠物

class Pet < ActiveRecord::Base

# Associations
has_and_belongs_to_many :owners

accepts_nested_attributes_for :owners, :reject_if => :all_blank
end

拥有者

class Owner < ActiveRecord::Base

# Associations
has_and_belongs_to_many :pets
has_one :phone_number, :as => :callable, :dependent => :destroy
has_one :address, :as => :addressable, :dependent => :destroy

accepts_nested_attributes_for :phone_number
accepts_nested_attributes_for :address
end

电话号码

class PhoneNumber < ActiveRecord::Base
belongs_to :callable, polymorphic: true
end

地址

class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end

我有一个顶级 form_for @pet,其中嵌套了 f.fields_for :ownersf.fields_for :phone_number f.fields_for :address 都嵌套在 f.fields_for :owners block 中。这意味着我的 params.require 看起来像这样。

params.require(:pet).permit(:name, :breed, :color, :neutered, :microchip, :flee_control,
:heartworm_prevention, :date_of_birth, :gender, :species_id, :avatar,
:owners_attributes => [ :first_name, :last_name, :email,
:phone_number_attributes => [:number],
:address_attributes => [:line1, :city, :state, :zip_code] ])

我的参数都是正确的,我可以创建新记录并且一切正常。当我尝试使用 :reject_if => :all_blank 拒绝空白所有者时,问题就来了。

因为有第二层嵌套属性,phone_number_attributesaddress_attributes 都被认为是 not_blank,因为它们在技术上属于 !ruby/hash:ActionController 类型::Parameters,它允许在不应该使用空白属性的情况下构建对象。

我已经搜索了大约 2 个小时,但找不到任何提及此问题的信息。我错过了一些明显的东西吗?我试过在电话号码和地址的所有者模型上添加 :reject_if => :all_blank 也没有走这条路。

编辑:我能够让它工作,但必须有更好的内置方法来做到这一点。

accepts_nested_attributes_for :owners, reject_if: proc { |attributes|
attributes.all? do |key, value|
if value.is_a? ActionController::Parameters
value.all? { |nested_key, nested_value| nested_key == '_destroy' || nested_value.blank? }
else
key == '_destroy' || value.blank?
end
end
}

最佳答案

我还没有看到一个内置的方法来完成你正在尝试做的事情,但我使用的解决方法是扩展 api 文档中的示例,如下所示:

# Add an instance method to application_record.rb / active_record.rb
def all_blank?(attributes)
attributes.all? { |key, value| key == '_destroy' || value.blank? || (all_blank?(value) if value.is_a?(Hash)) }
end

# Then modify your model pet.rb to call that method
accepts_nested_attributes_for : owners, reject_if: :all_blank?

来自 api 的原始示例

REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == "_destroy" || value.blank? } }

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

关于ruby-on-rails - 使用 :reject_if => :all_blank on double nested forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26621177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com