需要限制一篇文章的评论数,我的实现如下:
class Article < ActiveRecord::Base
  has_many :comments
  validates_length_of :comments, :maximum => 3, message: "最多有3个评论"
end
class Comment < ActiveRecord::Base
  belongs_to :article
  after_save :validate_comments_length_of_article
  private
  def validate_comments_length_of_article
    if article.comments.length > 2
      errors.add(:base, "文章最多有3个评论")
      return false
    end
  end
end
这样写有没有问题?还有没有其他更好的办法?