简体   繁体   中英

How to limit number of nested attributes for a model in rails

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 ??

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM