Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveRecord AssociationCollection build should set belongs_to association before calling block

#4940

activerecord/associations/association_collection.rb
Current implementation is this:

def build(attributes = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| build(attr, &block) }
  else
    build_record(attributes) do |record|
      block.call(record) if block_given?
      set_belongs_to_association_for(record)
    end
  end
end

By implementing the build like this:

def build(attributes = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| build(attr, &block) }
  else
    build_record(attributes) do |record|
      set_belongs_to_association_for(record)
      block.call(record) if block_given?
    end
  end
end

The callback can link to the associated object.
an example usage is:

  author.autobiographies.build do |book|
    book.title = "#{book.author.name}'s autobiography"
  end

Reported by 2 College Bums · June 23rd, 2010 @ 01:19 AM

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Neeraj Singh
    Neeraj Singh

    Can you add a failing test and also provide patch as per the guidelines. This looks interesting.

    June 23rd, 2010 @ 01:53 AM

  2. Santiago Pastorino
  3. Neeraj Singh
    Neeraj Singh
    • State changed from new to invalid
    • Importance changed from to Low

    Even with existing code you can do

    author.autobiographies.build do |book|
      book.title = "#{book.author.name}'s autobiography"
    end
    

    and it will work.

    September 8th, 2010 @ 09:39 PM

  4. Rohit Arondekar
    Rohit Arondekar
    • Tag changed from activerecord associations, activerecord, associations, build to activerecord, associations, build

    October 7th, 2010 @ 05:21 AM