Question

I'm trying to use MongoMapper in my Sinatra app for a simple auction site, but I'm having trouble running a simple query and getting any results.

before '/auction/:id' do
    connection = Mongo::MongoClient.new
    db = connection.db('auction')
    collection = db['auctions']

    @query = Plucky::Query.new(collection)
end

get '/auction/:id' do
    @auction = @query.where({:id => params["id"].to_i})
    "#{@auction.inspect}"
end

But I get no output with @auction.inspect in the browser. However, when I use the query @auction = @query.all I get all of the records within my database.

Params (when using url localhost/auction/3):

{"splat"=>[], "captures"=>["3"], "id"=>"3"}

query.all output:

[{"_id"=>BSON::ObjectId('529cbbee21f7f10dd4000005'), "id"=>2, "name"=>"jump", "price"=>1.42}, {"_id"=>BSON::ObjectId('529cbbf821f7f10dd400000e'), "id"=>3, "name"=>"here", "price"=>93.34}]
Was it helpful?

Solution

MongoMapper (or more accurately, Plucky, the library that builds MongoMapper queries) casts a field called id to _id automatically for parity with ActiveRecord, so you can't use two different fields called _id and id. You'll see that if you look at the generated query in your logs.

In this case, you'd want to use a different field name.

OTHER TIPS

.where builds the association, but you'll need to call a method like all or first to perform the query and get results:

@auction = @query.where({:id => params["id"].to_i}).first
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top