Ruby on Rails Tuesday, May 27, 2014

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?

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/14b8e119ec66555dd2b2cc2bbb44fb25%40ruby-forum.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment