0

I have two models which are related to one another (many to many) and I want to return them both in the response from my Rails controller action.

The two classes are User and Location. There is also a link class UserLocation.

User.rb looks like:

class User

  include DataMapper::Resource

  ...
  has n, :user_locations
  has n, :locations, :through => :user_locations

end

UserLocation.rb:

class UserLocation

  include DataMapper::Resource

  # attributes
  property :id, Serial

  # relationships
  belongs_to :user
  belongs_to :location

  # validation
  validates_presence_of :user, :location

end

Location.rb:

class Location

  include DataMapper::Resource

  # attributes
  # no need to specify the user relation AFAIK

end

When I do a User.get(id) it returns all the user attributes but not the locations. I can debug through the code and run a user.locations and it works correctly. Why aren't the locations being returned from the rails action?

Gerard
  • 4,688
  • 5
  • 48
  • 76

1 Answers1

0

That's how it should work. Relations are loaded with separate SQL request, it might be slow and complex, and you should specify exactly, which relation you want to load. Imagine loading all relations in one get call — it would me a mess.

ujifgc
  • 2,075
  • 1
  • 18
  • 20