Ruby on rails 简单字段-避免在所有字段都为空时创建

Ruby on rails 简单字段-避免在所有字段都为空时创建,ruby-on-rails,validation,simple-form,Ruby On Rails,Validation,Simple Form,我有一个供用户使用的表单,其部分如下所示: <%= f.simple_fields_for :uncles, User.new do |uncle| %> <%= uncle.input :first_name, :label => "First Name" %> <%= uncle.input :last_name, :label => "Last Name" %> <%= uncle.input :email%&g

我有一个供用户使用的表单,其部分如下所示:

<%= f.simple_fields_for :uncles, User.new do |uncle| %>
    <%= uncle.input :first_name, :label => "First Name" %>
    <%= uncle.input :last_name, :label => "Last Name" %>
    <%= uncle.input :email%>
<% end %>

假设您正在使用
接受
的_嵌套_属性_来创建相关模型,请添加一个以检查空白字段

accepts_nested_attributes_for :uncles, :reject_if => :reject_uncles?

def reject_uncles?(attributes)
  attributes[:first_name].blank? &&
  attributes[:last_name].blank? &&
  attributes[:email].blank?
end

我可能会尝试自定义验证器,例如:

(User model class)
validate :all_fields_required

private
def all_fields_required
  if first_name && last_name && email then
  # or perhaps: if (first_name != '') && (last_name != '') && (email != '') then
    true
  else
    false
  end
end

在您的情况下,您应该使用
接受
的嵌套属性,正如@Buck Doyle所说的。当您使用该方法时,您可以为父级和子级构建表单(如您所言),当您提交表单时,如果子级信息为空,则仅保存父级信息。那么如何为使用
接受嵌套的属性呢

在用户模型中,可以添加以下内容:

attr_accessible :uncles_attributes
accepts_nested_attributes_for :uncles, :reject_if => lambda { |attrs| attrs.all? { |key, value| value.blank? } }

仅此而已。现在在您的
User
控制器中,您只需使用
save
方法创建
User
对象,它会为您检查,如果叔叔(孩子)的信息为空,则只保存家长的信息。

不过我不想拒绝。我希望提交父表单,但要避免创建“叔叔”用户记录。
reject\u如果
应用于嵌套的叔叔属性。
用户
仍将被创建,只是没有空白的
叔叔
s。
attr_accessible :uncles_attributes
accepts_nested_attributes_for :uncles, :reject_if => lambda { |attrs| attrs.all? { |key, value| value.blank? } }