Question

Say I have two data mapper classes like this:

class Family
   include DataMapper::Resource

   property :id,   Serial
   property :nice, Boolean
end

Class Person
   include DataMapper::Resource

   property :id, Serial

   belongs_to :family
end

If I want to get all the people belonging to a certain family family, I can use this:

people=Person.all(:family=>family)

But what if I want to get all people who belong to a family which have the nice attribute? In SQL I could do

SELECT * FROM persons, families WHERE persons.family_id=families.id AND families.nice

Is there a nice way to do this in data mapper without dropping to the underlying dataset?

Was it helpful?

Solution

You need to specify that a Family has several Persons. See the documentation on has n and belongs_to.

class Family
  include DataMapper::Resource

  property :id,   Serial
  property :nice, Boolean

  # add this:
  has n, :people
end

Then you can use this:

Family.all(:nice => true).people

The SQL generated is actually a subquery rather than a join:

 SELECT "id", "family_id" FROM "people" WHERE "family_id" IN (SELECT "id" FROM "families" WHERE "nice" = 't') ORDER BY "id"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top