【问题标题】:Rails3 Cocoon Validate Nested Field CountRails3 Cocoon 验证嵌套字段计数
【发布时间】:2012-04-09 22:06:22
【问题描述】:

我在验证 cocoon 和模型允许的字段数时遇到问题。使用 cocoon、rails3,我有一个嵌套表单,我的位置有很多链接。

我需要将每个位置的链接数限制为 5 个。

在我的 location.rb 模型中,我有这个:

 class Location < ActiveRecord::Base

   has_many :links
   accepts_nested_attributes_for :links, :reject_if => lambda { |a| a[:link_name].blank? }, :allow_destroy => true   
   validate :check_link_count

   ...

   def check_link_count
      if self.links.count > 5
        self.errors.add :base, "No more than 5 links allowed."
      end
   end

   ...

最多添加 5 个链接,一切正常。

如果我添加 6 个链接并保存,我会收到错误消息。也不错。

问题是当我尝试删除链接时 - 似乎链接仅在保存后才被删除(我认为)。如果我因此删除所有字段,我仍然会收到错误消息。

有什么建议吗?是否有其他验证方式?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 cocoon-gem


    【解决方案1】:

    嗯。你可以试试这样的

     def check_link_count
        if self.links.reject(&:marked_for_destruction?).count > 5
          self.errors.add :base, "No more than 5 links allowed."
        end
     end
    

    【讨论】:

    • 太棒了,这很容易。必须阅读marked_for_destruction S。
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多