为什么我的模型中的reject_if不拒绝空白记录?

时间:2015-11-12 10:22:32

标签: ruby-on-rails

在以下课程中......

train.Projects.Add(project);

...我添加了一些代码,如果他们的字段为空,我希望阻止'亲戚'保存在父模型上。它似乎不起作用。它保存了空白和非空白字段。

即。当我进入控制台并查询数据库时,我可以拉出父记录并运行如下查询:

class Parent < ActiveRecord::Base
  has_many :relatives
  has_many :kids, through: :relatives

  accepts_nested_attributes_for :relatives,
    :reject_if => lambda { |a| a['kid_id'].blank? },
    :allow_destroy => true
end

这就是我的预期 - 我输入了'孩子'的数据。

2.2.2 :004 > p.relatives.find(17)
  Relative Load (5.4ms)  SELECT  "relatives".* FROM "relatives" WHERE "relatives"."parent_id" = ? AND "relatives"."id" = ? LIMIT 1  [["parent_id", 24], ["id", 17]]     
 => #<Relative id: 17, relationship: "yes", parent_id: 24, kid_id: 1, created_at: "2015-11-12 09:56:07", updated_at: "2015-11-12 09:56:07">

此记录永远不会保存,因为它违反了上面的lambda,即......

2.2.2 :005 > r = p.relatives.find(18)
  Relative Load (3.4ms)  SELECT  "relatives".* FROM "relatives" WHERE "relatives"."parent_id" = ? AND "relatives"."id" = ? LIMIT 1  [["parent_id", 24], ["id", 18]]
 => #<Relative id: 18, relationship: "", parent_id: 24, kid_id: nil, created_at: "2015-11-12 09:56:07", updated_at: "2015-11-12 09:56:07"> 

......字段是空白的!

这是有问题的控制器(摘录):

2.2.2 :006 > r.relationship.blank?
 => true 
2.2.2 :007 > r.kid.blank?
 => true 

3 个答案:

答案 0 :(得分:3)

我认为这可能会有所帮助

https://fabianosoriani.wordpress.com/2011/06/07/accepts_nested_attributes_for-3-0-5-reject_if-still-have-gotchas/

accepts_nested_attributes_for背后有一些问题需要验证。

答案 1 :(得分:0)

根据我的理解,因为模特孩子与亲属关联,你应该这样做。在您的父模型

中尝试此操作
  accepts_nested_attributes_for :relatives, :allow_destroy => true

然后在你的相对模型中,

accepts_nested_attributes_for :kids,
    :reject_if => lambda { |a| a['kid_id'].blank? },
    :allow_destroy => true

答案 2 :(得分:0)

感谢@ user5554692,发现执行此操作的唯一方法如下:

将其添加到父控制器:

parent_params[:relatives_attributes].delete_if { |k,v| v['kid_id'].blank?}

删除所有空白记录,然后......

@parent = Parent.new(parent_params)

照常创建父对象。

显然,出于某种原因,reject_if在这种特殊情况下不起作用。