This project is archived and is in readonly mode.

#4940 ✓invalid
2 College Bums

ActiveRecord AssociationCollection build should set belongs_to association before calling block

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

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

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Pages