This project is archived and is in readonly mode.
association#build inconsistency
-
Pratik
- Assigned user set to Michael Koziarski
- State changed from new to wontfix
Please reopen once we have a patch for this.
This looks similar to an ID map patch Koz has been involved with, so assigning the ticket to him.
-
Prem Sichanugrist (sikachu)
I just wonder ..
I've looked at the code, and I found out that the association's build method is done by setting
foreign_keyto be the parent'sid. Can we also do something like set the attribute with the name of the parent object to be refer to parent object? -
Ryan Bigg
- State changed from wontfix to open
Marked a similar ticket, #4497 ActiveRecord associations .build does not set associations., as a duplicate of this one and asked the user to submit a patch here.
-
Evgeniy Dolzhenko
Btw. shouldn't
:inverse_ofassociation options handle this? -
Andreas Mayer
Have the same problem. Using the workaround. Will this be fixed in Rails 3 final?
-
Neeraj Singh
- State changed from open to resolved
- Importance changed from to Low
As Evgeniy Dolzhenko suggested setting inverse_of resolves the issue.
class Car < ActiveRecord::Base has_many :brakes, :inverse_of => :car end class Brake < ActiveRecord::Base belongs_to :car, :inverse_of => :brakes end> Car.first.brakes.build.car Car Load (0.4ms) SELECT "cars".* FROM "cars" LIMIT 1 => #<Car id: 1, name: nil> > Car.new.brakes.build.car => #<Car id: nil, name: nil> > Car.create.brakes.build.car SQL (0.5ms) INSERT INTO "cars" ("name") VALUES (NULL) => #<Car id: 2, name: nil> > Car.last.brakes.find_or_initialize_by_name('cool').car Car Load (0.6ms) SELECT "cars".* FROM "cars" ORDER BY cars.id DESC LIMIT 1 Brake Load (0.2ms) SELECT "brakes".* FROM "brakes" WHERE ("brakes".car_id = 2) AND ("brakes"."name" = 'cool') LIMIT 1 Car Load (0.1ms) SELECT "cars".* FROM "cars" WHERE ("cars"."id" = 2) LIMIT 1 => #<Car id: 2, name: nil> > Car.last.brakes.find_or_create_by_name('cool').car Car Load (0.4ms) SELECT "cars".* FROM "cars" ORDER BY cars.id DESC LIMIT 1 Brake Load (0.3ms) SELECT "brakes".* FROM "brakes" WHERE ("brakes".car_id = 2) AND ("brakes"."name" = 'cool') LIMIT 1 SQL (0.3ms) INSERT INTO "brakes" ("car_id", "name") VALUES (2, 'cool') => #<Car id: 2, name: nil>tested with rails edge.