[英]How to limit number of nested attributes for a model in rails
我有两个相关的模型:Group和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
我想要做的是添加一个验证,以防止member_count达到25后立即添加成员。
因此,如果我编辑一个组,请举例说:
它应保存前5个记录,然后引发错误,例如“您已超出嵌套属性的限制”。
在rails中是否有任何内置方法来执行此操作。 作为一个比较新手的铁路我不知道这个?
在你的模型中:
accepts_nested_attributes_for :field, limit: 10
在您的保存方法中:
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
我也不知道任何内置方法。 您可以添加自己的验证例程。
validate :member_limit
def member_limit
errors.add(:base, "You sir, have too many members!") if members.count > 25
end
这会给基本模型增加一个错误。 我认为您还可以使用members.errors.add(:base, "Sorry, no room for you.")
来为25以上的关联添加错误members.errors.add(:base, "Sorry, no room for you.")
以下是阅读更多内容的指南:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#performing-custom-validations
您是否尝试在嵌套属性上使用限制选项?
accepts_nested_attributes_for :field, limit: 10
您可以限制可以创建多少嵌套关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.