ActiveRecord::NestedAttributes::TooManyRecords 错误

ActiveRecord::NestedAttributes::TooManyRecords error

在我的应用程序中,当用户注册时,他们可以上传一些文件。我需要将上传限制为最多 5 个文件。所以我有两个模型,代码如下

class User < ActiveRecord::Base
has_many :fileuploads, :dependent => :destroy

accepts_nested_attributes_for :fileuploads, limit: 5, :allow_destroy => true

  validate do |user|
    if user.fileuploads && user.fileuploads.count > 5
      errors[:base] << "You can add maximum 5 files."
    end
  end  
end

class Fileupload < ActiveRecord::Base
  belongs_to :user
end

并在我的创建和更新操作中添加了

respond_to do |format|
  begin
    if @user.save
      format.html { redirect_to @user, notice: I18n.t('views.flash_messages.user_was_successfully_created') }
    else
      format.html { render action: "new" }
    end
  rescue ActiveRecord::NestedAttributes::TooManyRecords
    flash[:error] = 'You can add maximum 5 files. '
  end
end

正如您从上面的代码中看到的那样,我正在使用 limit: 5 以及 validate 回调。但是当我更新用户时,两者都很完美。但是当创建用户时,这个错误消息根本没有被挽救。我收到此错误,

ActiveRecord::NestedAttributes::TooManyRecords in UsersController#create
Maximum 5 records are allowed. Got 7 records instead.

那么,为什么限制和验证在用户更新期间起作用但在用户创建期间不起作用?以及如何让它也适用于创建操作?

这就是现在对我有用的东西。欢迎更好的解决方案。

class User < ActiveRecord::Base
has_many :fileuploads, :dependent => :destroy

accepts_nested_attributes_for :fileuploads, limit: 5, :allow_destroy => true

after_create :count_files

def count_files
    if self.fileuploads && self.fileuploads.count > 5
      errors[:base] << "You can add maximum 5 files."
      raise ActiveRecord::Rollback
    end
end