Read more

Machinist's #make breaks on has_many associations when defining method `empty?`

Martin Straub
September 07, 2011Software engineer at makandra GmbH

Observed on Rails 2.3 and machinist 1.0.6

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Like the title says, when you define the method empty? like in the following example, you may not longer use collection.make.

class Book

  has_many :pages

  def empty?
    pages.empty?
  end

end

Assuming

b1 = Book.find(1)
b2 = Book.find(2)

instead of expected

b1.pages.make #=> #<Page id: 1, book_id: 1>
b2.pages.make #=> #<Page id: 2, book_id: 2>

you'll get

b1.pages.make #=> #<Page id: 1, book_id: 3>
b2.pages.make #=> #<Page id: 2, book_id: 4>

So if you want to keep your empty? method, from now on you have to write

page = Page.make(:book => b1)

to reliably add records to the collection.

Posted by Martin Straub to makandra dev (2011-09-07 10:22)