Reputation: 1488
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?
Upvotes: 1
Views: 61
Reputation: 79723
You need to specify that a Family
has several Person
s. 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"
Upvotes: 1