所以我有以下模型
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 :owners
,f.fields_for :phone_number
和f.fields_for :address
都嵌套在f.fields_for :owners
块中。这意味着我的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_attributes
和address_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
}
答案 0 :(得分:1)
我还没有看到一种内置的方法来完成你想要做的事情,但是我使用的解决方法是扩展api文档中的示例,如下所示:
X-XSRF-TOKEN
来自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?
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html