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.

Inconsistent behavior of collection.new vs collection.build

#6618

I'm not sure how exactly collection.new should behave, as it's not really documented (at least not here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassM..., but it's behavior is inconsistent:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
end

user.friendships.new
user.friendships # => []
user.friendships.build
user.friendships # => [#<Friendship id: nil, user_id: 1, friend_id: nil>]

# but
user.friends # => []
user.friends.new
user.friends # => [#<User id: nil...>]

I'm not sure how it should behave, but it would be great if it always behaved like for non-through associations. It works like this in Rails 3.0.5 and master.

Reported by Szymon Nowak · March 24th, 2011 @ 07:42 PM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Szymon Nowak
    Szymon Nowak

    Turns out that HasManyThroughAssociation has a simple alias: alias_method :new, :build, which HasManyAssociation doesn't have. Not sure if it's on purpose.

    March 24th, 2011 @ 07:51 PM