I'm using Rails 1.2.3 (yeah, I know) and am confused about how has_many
works with respect to object persistence.
For the sake of example, I'll use this as my declaration:
class User < ActiveRecord::Base
has_many :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :user
end
As I understand it, this generates, among others, a method User#assignments.build
, which creates an Assignment
object whose user_id
is the receiving instance's id
(and whose other fields are as specified in the argument), but does not save this object in the database. The object can be saved later by calling Assignment#save!
.
However, The Pragmatic Programmers' Agile Web Development with Rails, Second Edition, which I've been using as a tutorial and reference, says:
If the parent object exists in the database, then adding a child object to a collection automatically saves that child.
There seems to be a contradiction here. What I'd like to know is:
- If I do
some_user.assignments.build
, is theAssignment
object saved? - If I do
some_user.assignments << Assignment.new
, is theAssignment
object saved? - If I do
some_user.assignments << Assignment.create
, are two database calls made, or just one? What about if I modify theAssignment
object between creating it and adding it tosome_user.assignments
? - What happens if I
save!
anAssignment
object whose correspondingUser
has not yet been saved in the database?
P.S. The reason I don't just use User#assignments.create
for everything is because it doesn't let me farm out initialization to an external method, which I'd like to be able to do. I also don't want to make multiple trips to the database.