I’m using DataMapper in Sinatra (not Rails, but hopefully close
enough - I’m new!)
I have created a model similar to this:
class Server
include DataMapper::Resource
property :id, Serial
property :name, String
property :ip, String
has n, :serverTables
has n, :tables, :through => :serverTables
end
class Table
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :serverTables
has n, :servers, :through => :serverTables
end
class ServerTable
include DataMapper::Resource
property :id, Serial
property :enabled, Boolean
belongs_to :server
belongs_to :table
end
have to do this twice because there is no way to select fields from
joining table in DataMapper!
@enabled_tables = @server.serverTables.all(:enabled => true).tables
@disabled_tables = @server.serverTables.all(:enabled => false).tables
What I cannot figure out is how to get a dataset back that includes the
‘enabled’ field from the joining table in the many-to-many relationship.
The best I can do is run 2 queries to get each set, which saves me from
checking for each individual record. But I know that it can be condensed
into a single query very easily by simply adding another select field
referencing the join table.
@servers.tables -
SELECT “tables”.“id”, “tables”.“name” FROM “tables” INNER JOIN
“server_tables” ON “tables”.“id” = “server_tables”.“table_id” INNER JOIN
“servers” ON “server_tables”.“server_id” = “servers”.“id” WHERE
“server_tables”.“server_id” = 1 GROUP BY “tables”.“id”, “tables”.“name”
ORDER BY “tables”.“id”
The only change is to add “server_tables”.“enabled” to the outermost
select.
Has anyone else encountered this and figured out a solution?