Ruby on rails 使用:拒绝_if=>;:双嵌套窗体上的所有\u空格
因此,我有以下模型 宠物 我的参数都是正确的,我可以创造新的记录,一切正常。当我尝试使用Ruby on rails 使用:拒绝_if=>;:双嵌套窗体上的所有\u空格,ruby-on-rails,ruby,Ruby On Rails,Ruby,因此,我有以下模型 宠物 我的参数都是正确的,我可以创造新的记录,一切正常。当我尝试使用:reject\u if=>:all\u blank来拒绝空白所有者时,就会出现问题 由于存在第二级嵌套属性,phone\u number\u属性和address\u属性都被视为非空属性,因为它们在技术上属于类型!ruby/hash:ActionController::Parameters,它允许在不应该使用空属性时使用空属性构建对象 我已经搜索了大约2个小时了,我找不到任何关于这个问题的内容。我错过了什么明
:reject\u if=>:all\u blank
来拒绝空白所有者时,就会出现问题
由于存在第二级嵌套属性,phone\u number\u属性
和address\u属性
都被视为非空属性,因为它们在技术上属于类型!ruby/hash:ActionController::Parameters
,它允许在不应该使用空属性时使用空属性构建对象
我已经搜索了大约2个小时了,我找不到任何关于这个问题的内容。我错过了什么明显的东西吗?我已经尝试在所有者模型上添加电话号码和地址的:reject\u if=>:all\u 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? } }
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
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] ])
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
}
# 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?
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == "_destroy" || value.blank? } }