I would like to be able to make dynamic queries with DataMapper ,for searching an Sqlite database for my Sinatra project.Is it possible? So far I have come up with something like this trying to get the songs that are sang from the artist specified by the named parameter:

get '/artists/:name' do
@artist = Artist.get(params[:name])
@songs= Song.all(:artist_name => '#{artist.name}')
slim :show_artists
end

These are my DataMapper Classes:

configure:development do
    DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/3sbase.db")
    DataMapper.auto_migrate!
end

class Song
    include DataMapper::Resource
    property :id, Serial
    property :title, String
    property :year, Integer
    belongs_to :artist
end

class Artist
    include DataMapper::Resource
    #property :id, Serial
    property :name, String, :key=>true
    property :age, Integer
    has n, :songs
end




DataMapper.finalize

and this is my .slim file

/show_artists.slim

h1= @artist.name
p Age: #{@artist.age}

- if @songs.any?
    ul#songs
      -@songs.each do |song|
        p <a href="/songs/#{song.id}">#{song.title} </a>
- else
  p There are no songs from this artist/band in the database.

Every time the if statement returns false and so I get the "There are no songs from this artist/band in the database." message despite the fact that there are songs sang by the artist I search for in my database.

有帮助吗?

解决方案

After asking in the sinatrarb google group I was suggested to change

@songs= Song.all(:artist_name => '#{artist.name}') 

with this line:

@songs= Song.all(:artist => {:name => @artist.name})

or with this

@songs= @artist.songs

they both work fine

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top