I'm trying to build a small model consisting of two entities. For the purposes of this question, call them A
and B
. A
has a one-to-many relationship to several B
s; this means that each B
belongs_to
an A
.
In this particular case, I'd like to call the relationship from B
back to A
something other than a
. I think I got close with the following:
class A
include DataMapper::Resource
property :id, Serial
has n, :bs
end
class B
include DataMapper::Resource
property :id, Serial
belongs_to :owner, 'A'
end
The important bit here is the belongs_to :owner, 'A'
line in B
. With this, I can successfully:
A
A
for its bs
and get an empty array backB
, assigning its owner
to be the A
I made earlierHowever, when I go to save that instance of B
, I run into trouble – calling save
returns false
. If I print the B
, I see that it has two attributes: one called owner_id
and another called a_id
.
What else do I need to do with this model to rename the relationship from B
back to A
? Is such a rename even possible?
Figured it out. The owning entity (A
) needs to explicitly specify the child keys that it wants created for the relationship:
class A
include DataMapper::Resource
property :id, Serial
has n, :bs, :child_key => [ 'owner_id' ]
end
class B
include DataMapper::Resource
property :id, Serial
belongs_to :owner, 'A'
end
With this change, I only see one relationship attribute created on B
, and I'm able to save instances of B
that I create.