使用:reject_if => :双嵌套表单上的all_blank

时间:2014-10-29 01:03:31

标签: ruby-on-rails ruby

所以我有以下模型

宠物

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_numberf.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_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
  }

1 个答案:

答案 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

相关问题