验证 Ruby on Rails 中 has_many 项的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4836897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validate the number of has_many items in Ruby on Rails
提问by sbonami
Users can add tags to a snippet:
用户可以向片段添加标签:
class Snippet < ActiveRecord::Base
# Relationships
has_many :taggings
has_many :tags, :through => :taggings
belongs_to :closing_reason
end
I want to validate the number of tags: at least 1, at most 6. How am I about to do this? Thanks.
我想验证标签的数量:至少 1 个,最多 6 个。我该怎么做?谢谢。
回答by Nikita Rybak
You can always create a custom validation.
您始终可以创建自定义验证。
Something like
就像是
validate :validate_tags
def validate_tags
errors.add(:tags, "too much") if tags.size > 5
end
回答by sbonami
A better solution has been provided by @SooDesuNeon this SO post
@SooDesuNe在这篇 SO post上提供了更好的解决方案
validates :tags, length: { minimum: 1, maximum: 6 }
回答by asukiaaa
I think you can validate with using .reject(&:marked_for_destruction?).length.
我认为您可以使用.reject(&:marked_for_destruction?).length.
How about this?
这个怎么样?
class User < ActiveRecord::Base
has_many :groups do
def length
reject(&:marked_for_destruction?).length
end
end
accepts_nested_attributes_for :groups, allow_destroy: true
validates :groups, length: { maximum: 5 }
end
Or this.
或这个。
class User < ActiveRecord::Base
has_many :groups
accepts_nested_attributes_for :groups, allow_destroy: true
GROUPS_MAX_LENGTH = 5
validate legth_of_groups
def length_of_groups
groups_length = 0
if groups.exists?
groups_length = groups.reject(&:marked_for_destruction?).length
end
errors.add(:groups, 'too many') if groups_length > GROUPS_MAX_LENGTH
end
end
Then, you can command.
然后就可以指挥了。
@user.assign_attributes(params[:user])
@user.valid?
Thank you for reading.
感谢您的阅读。
References:
参考:
http://homeonrails.com/2012/10/validating-nested-associations-in-rails/http://qiita.com/asukiaaa/items/4797ce44c3ba7bd7a51f
http://homeonrails.com/2012/10/validating-nested-associations-in-rails/ http://qiita.com/asukiaaa/items/4797ce44c3ba7bd7a51f

