Rails嵌套模型和子验证

时间:2017-10-31 21:20:41

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

我有两个模特。

示例:

class Book < ActiveRecord::Base
  has_many :pages, dependent: :destroy
  accepts_nested_attributes_for :pages, allow_destroy: true
end

class Page < ActiveRecord::Base
  belongs_to :book

  validate_on_create :count_within_bounds

  LIMIT = 200

  private

  def count_within_bounds
    if self.book.pages.count >= LIMIT
      errors.add_to_base("Number of pages cannot be greater than #{LIMIT}")
    end
  end
end

现在,当通过嵌套表单更新书籍时,一切正常。我可以编辑让我们说出标题并添加新页面。但是,如果页面验证失败,则对书籍模型所做的其他更改也不会被保存。

我知道它在一个事务中都被保存了但是有没有办法在不必手动分两步的情况下保持父级,即首先保存父级而不使用pages_attributes?

2 个答案:

答案 0 :(得分:1)

您可以取消验证并执行以下操作:

<%= form_for(@book) do |f| %> 
    # book attribute stuff....

      <% if @book.pages.count < 200 %>
            <%= f.fields_for :pages, @book.pages.create do |ff| %>
            <%= ff.text_field :attribute %><br>
           <% end %>
         <% end %>
  <% end %>

现在,只有少于200页的图书才能获得包含添加页面的字段的表单。

答案 1 :(得分:0)

如果您只想保存父级并跳过Page子类的验证,则可以使用Book模型中的validate选项。< / p>

class Book < ActiveRecord::Base
  has_many :pages, validate: false, dependent: :destroy
end