3

I have two related models : Group and Member.

Group.rb :

has_many :members, :dependent => :destroy
accepts_nested_attributes_for :members, :reject_if => lambda { |a| a[:email].blank? and a[:id].blank? }, :allow_destroy => true

What I want to do is adding a validation which prevents adding members as soon as members_count reaches 25.

So if I edit a Group, let's say for example :

  1. I have 20 existing members
  2. I add 8 more members from FORM at my browser end

It should saves the first 5 records and then raises an error such as "You have exceeded limit for the nested attributes".

Is there any built-in method in rails to do this. Being a comparatively newbie to rails I am not aware of this ??

siekfried
  • 2,964
  • 1
  • 21
  • 36
Sahil Grover
  • 1,862
  • 4
  • 26
  • 57
  • similar question here : http://stackoverflow.com/questions/7863618/rails-3-1-limit-user-created-objects – siekfried Jan 16 '13 at 19:11

3 Answers3

11

In your model :

accepts_nested_attributes_for :field, limit: 10

In your save method:

def update
  begin
    # normal model update
    if Model.update_attributes(params[:your_model])
      flash[:notice] = 'Save success'
    else
      flash[:error] = 'Save error'
    end
  rescue ActiveRecord::NestedAttributes::TooManyRecords
    flash[:error] = 'Too many records'
  end
end
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
6

I'm not aware of any built-in method either. You could add your own validation routine though.

validate :member_limit

def member_limit
  errors.add(:base, "You sir, have too many members!") if members.count > 25
end

This adds an error to the base model. I think you could also add errors to the associations above 25 with members.errors.add(:base, "Sorry, no room for you.")

Here is the guide to read more:

http://guides.rubyonrails.org/active_record_validations_callbacks.html#performing-custom-validations

Geoff
  • 2,208
  • 1
  • 16
  • 17
  • It's the best approach of the answers because it doesn't check only for current request's nested attributes but also for already existing nested attributes of the model. – Artur Haddad Sep 26 '17 at 20:56
6

Have you tried to use limit option on nested attributes?

    accepts_nested_attributes_for :field, limit: 10

You can limit how many nested association can be created.

bernardeli
  • 71
  • 3