Rails ActiveRecord: skip checks for associations

I will ask this question again because the code and the example are incorrect (it really works in the case shown).

Given these models:

class Author < ActiveRecord::Base
  has_many :books
  validates_presence_of :email
end

class Book < ActiveRecord::Base
  belongs_to :author
  validates_presence_of :title
end

We can skip the checks when creating the book:

b = Book.new
b.save(:validate => false)

But if we retrieve an invalid book from the database and assign its associations to Author, we are not allowed to save Author:

a = Author.new
a.email = "foo"
a.books = Book.all
a.save!

This is mistake:

ActiveRecord :: RecordInvalid: validation failure: invalid books

How to skip validations for related book models without missing them for the author?

Note that speaking has_many :books, :validate => falsein Author does not help: the association is silently discarded while retaining the Author.

+3
1

class Author < ActiveRecord::Base
  has_many :books, :validate => false
  validates_presence_of :email
  after_save :save_invalid_books

  def save_invalid_books
    books.each do |b|
      b.save(false)
    end
  end
end

, validate = > false , , author_id. , , , ( (false)) .

, , , , , .

+11

Source: https://habr.com/ru/post/1779308/


All Articles