1

我有一个用户的表单,它的一部分看起来像这样:

<%= 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 %>

我的问题是:如果 simple_fields 中的所有字段都为空,我将如何避免创建此“叔叔”用户记录?

在我的用户模型中,我有这个:

has_many     :uncles,
             :through               => :uncles_relationships,
             :source                => :uncle
4

3 回答 3

0

假设您正在使用accepts_nested_attributes_for创建相关模型,请添加一个reject_if以检查空白字段。

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
于 2012-11-17T17:50:30.127 回答
0

accepts_nested_attributes_for正如@Buck Doyle 所说,在您的情况下,您应该需要使用。当您使用该方法时,您可以为父母和孩子建立一个表单(如您所说),当您提交表单时,如果孩子的信息为空,则只会保存父母的信息。那么如何使用accepts_nested_attributes_for呢?

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

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

就这些。现在在你的User控制器中,你只需要使用save方法来创建User对象,它会检查你,如果叔叔(孩子)的信息是空白的,只保存父母的信息。

于 2012-11-17T19:05:49.450 回答
0

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

(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
于 2012-11-17T18:22:20.337 回答