Ruby on rails 如果要限制嵌套记录的数量,如何编写代码?

Ruby on rails 如果要限制嵌套记录的数量,如何编写代码?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有两个模型 社区 社区话题 社区有许多社区主题 但是如果我想限制一个社区拥有的社区主题的数量,该怎么办? 我想把一个社区可以拥有的记录限制在1000条以内 如何在控制器的新操作中使用flash错误消息对其进行编码? 我应该在models/community\u topics.rb中编写什么代码?您需要在community topic模型中添加验证,它可以命名为check\u limits def check_limits if self.community.communitytopic

我有两个模型

  • 社区
  • 社区话题
社区有许多社区主题

但是如果我想限制一个社区拥有的社区主题的数量,该怎么办? 我想把一个社区可以拥有的记录限制在1000条以内

如何在控制器的新操作中使用flash错误消息对其进行编码?
我应该在models/community\u topics.rb中编写什么代码?

您需要在
community topic
模型中添加验证,它可以命名为
check\u limits

def check_limits
  if self.community.communitytopics.count == 1000
    self.errors.add("can't create more topics for this community")
    false
  else
    true
  end
end
我建议使用常数,而不是仅仅写1000,以防以后需要更改它