简体   繁体   English

如何在rails中限制模型的嵌套属性数

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

I have two related models : Group and Member. 我有两个相关的模型:Group和Member。

Group.rb : 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. 我想要做的是添加一个验证,以防止member_count达到25后立即添加成员。

So if I edit a Group, let's say for example : 因此,如果我编辑一个组,请举例说:

  1. I have 20 existing members 我有20个现有成员
  2. I add 8 more members from FORM at my browser end 我在浏览器端添加了8个来自FORM的成员

It should saves the first 5 records and then raises an error such as "You have exceeded limit for the nested attributes". 它应保存前5个记录,然后引发错误,例如“您已超出嵌套属性的限制”。

Is there any built-in method in rails to do this. 在rails中是否有任何内置方法来执行此操作。 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.") 我认为您还可以使用members.errors.add(:base, "Sorry, no room for you.")来为25以上的关联添加错误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 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. 您可以限制可以创建多少嵌套关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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