← Back to Upcase

has_one relationship: build_foo vs create_foo

(Deacon Bradley) #1

Suppose I have two models: Person & House. A Person :has_one House (and a House :belongs_to a Person).

I can create a new House for a Person and everything is wired up correctly. I can even create another new House for that same Person (which automatically deletes the old house and associates the new house). So I’m all good there.

What confuses me is the difference between person.build_house and person.create_house. I believe build_house should build the record, but not save it, which is what I want to do.

The problem I have is when I call person.build_house it is automatically destroying (or disassociating) the original house record immediately.

Am I misinterpreting the docs? Or perhaps doing something I shouldn’t be trying to do in the first place? :).

(Geoff Harcourt) #2

This might be a violation of checking for nil, but I think you could probably get your object doing something like this:

house_to_do_stuff_to = person.house || person.build_house

Then you could make whatever changes you wanted to the house and save it without worrying whether the house was new or not, and the build_house method wouldn’t blow away your existing house.

(Deacon Bradley) #3

Thanks! That’s more or less what I wound up doing. I guess I was just surprised to discover that calling build_house would remove the original person.house association without persisting the new one.