Clay Shirky
Clay Shirky

Reputation: 133

In Ruby/Sinatra, Datamapper's .all works but .get doesn't?

I am trying to take data from a path in Sinatra, and use it to look up a particular record using Datamapper. The Datamapper docs seem to indicate that.

get "/test/:test_path" do
    test_get = Intake.get( params[:test_path] )
    # Do stuff
    erb :blah_blah_blah
end

should find any records associated with the symbol :test_path

This does not work. test_get gets nil.

Meanwhile, what does work is

get "/test/:test_path" do
    test_all = Intake.all(:test_path => params[:test_path] )
    # Do stuff
    erb :blah_blah
end

My two questions are:

  1. What am I doing wrong with the .get() call in Datamapper?
  2. Is the .all(:name => value) method slower than .get(), or does it not matter which I use?

Here's a Sinatra script pared down to demonstrate the behavior.

#!/usr/bin/env ruby

require 'rubygems'
require 'sinatra'
require 'dm-core'
require 'dm-timestamps'

DataMapper.setup(:default, {:adapter => 'yaml', :path => 'db'})

class Intake
  include DataMapper::Resource

  property :id,         Serial
  property :created_at, DateTime
  property :test_path,  String
end

get "/test/:test_path" do

  test_all = Intake.all(:test_path => params[:test_path] )
  puts 'test_all:' test_all.inspect

  test_get = Intake.get( params[:test_path] )
  puts 'test_get:' test_get.inspect

  "Hello World!"
end

Upvotes: 1

Views: 331

Answers (1)

Reactormonk
Reactormonk

Reputation: 21700

#get only does a lookup based on primary key, with is the id. So

Intake.get(params[:test_path])

looks for something with id params[:test_path], which will fail. Use

Intake.first(test_path: params[:test_path])

Upvotes: 1

Related Questions