views:

38

answers:

2

Hello, I am using datamapper in a ruby application and I'm facing a problem I do not understand.

I have a Appartment model and a Location model. An appartment is at a given location and several appartments can be at the same location. This typically described a 1-n relationship (I guess :-) )

My feeeling is that in the Appartement sql table I need a location_id but I do not want any Appartment pointers within the Location table. For me, Location should live on its own and should not reference appartment.

In the Appartement ruby class, I have added:

has n, Location

but it then creates an appartment_id within the Location ruby class, which I do not want.

Would you have any clue ?

Thanks a lot, Luc

+1  A: 

It is one-to-many relationship but for Location model, not for Appartment. It means that Location can have many appartments and it is what you want, so Appartment model will have location_id. What you did is that you told datamapper that your Appartment has many locations, so it added appartment_id to Location.

To fix it you can add:

has n, Appartment

in Location class.

I don't know datamapper at all, but in Rails you can define it in both models. In Appartment you define something like:

belongs_to Location

and in Location you add something like my first example.

klew
Thanks, I will test this as soon as I get home :-)
Luc
A: 

I would just say

class Apartment
  belongs_to :location
end

class Location
  has n, :apartments
end

this would allow you to reference @apartment.location and @location.apartments

jing