嵌套表单关联模型获取自动保存

时间:2016-02-10 08:00:37

标签: ruby-on-rails nested-attributes

我的关联模型已自动保存。我希望只有当这些字段包含任何值时才会发生这种情况。显然reject_if是实现这一目标的方法,但我无法让它发挥作用。我已经尝试了:new_record?并传递了Proc。但我怀疑其他地方有问题,因为下面的reject_posts方法没有被调用。

has_one :reservation, as: :reservable,  autosave: false,
                      class_name: Booking::Reservation
accepts_nested_attributes_for :reservation, reject_if: :reject_posts

def reject_posts(attributed)
  binding.pry
end

我将如何尝试调试此内容?

1 个答案:

答案 0 :(得分:0)

  

我将如何尝试调试此内容?

第一步是确保您的流程正在调用accepts_nested_attributes_for方法。

简单检查是确定您的请求控制台日志是否将参数发送为...

parameters: {
   "model" => {
     "reservation_attributes" => {...}
   }
} 

如果您的参数没有显示_attributes,则您的fields_for或流量不正确。

-

您还应该确保class_name选项通过string

has_one :reservation, as: :reservable, class_name: "Booking::Reservation"

我个人会做以下事情:

#app/models/model.rb
class Model < ActiveRecord::Base
  has_one :reservation, as: :reservable, class_name: "Booking::Reservation", inverse_of: :model
  accepts_nested_attributes_for :reservation, reject_if: :all_blank?
end

“拒绝”是not validation。它只是阻止关联对象传递给嵌套模型...

  

如果未能通过您的条件,您也可以将:reject_if转发设置为默默忽略任何新的记录哈希值

我在其他模型上使用验证(使用inverse_of):

#app/models/reservation.rb
class Reservation < ActiveRecord::Base
  belongs_to :model, inverse_of: :reservation
  validates :x, :y, :z, presence: true
end

-

如果您想根据特定属性为空白拒绝,则应使用:

#app/models/model.rb
class Model < ActiveRecord::Base
  has_one :reservation, as: :reservable, class_name: "Booking::Reservation"
  accepts_nested_attributes_for :reservation, reject_if: proc { |a| a['name'].blank? || a['title'].blank? }
end