Sinatra 使用DataMapper进行动态查询

Sinatra 使用DataMapper进行动态查询,sinatra,ruby-datamapper,slim-lang,Sinatra,Ruby Datamapper,Slim Lang,我希望能够使用DataMapper进行动态查询,以便为我的Sinatra项目搜索Sqlite数据库。可能吗? 到目前为止,我已经想出了类似这样的方法,试图从命名参数指定的艺术家那里获得歌曲: get '/artists/:name' do @artist = Artist.get(params[:name]) @songs= Song.all(:artist_name => '#{artist.name}') slim :show_artists end 以下是我的DataMapper类

我希望能够使用DataMapper进行动态查询,以便为我的Sinatra项目搜索Sqlite数据库。可能吗? 到目前为止,我已经想出了类似这样的方法,试图从命名参数指定的艺术家那里获得歌曲:

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

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
这是我的.slim文件

/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.
/show\u artists.slim
h1=@artist.name
p年龄:#{@artist.Age}
-如果@songs.any?
ul#歌曲
-@歌曲。每首歌|
P
-否则
p数据库中没有来自此艺术家/乐队的歌曲。

每次if语句返回false时,我都会收到“数据库中没有来自此艺术家/乐队的歌曲”的消息,尽管我在数据库中搜索到了艺术家演唱的歌曲。

在Sinatrab谷歌群中询问后,有人建议我更改

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

@songs= Song.all(:artist => {:name => @artist.name})
还是用这个

@songs= @artist.songs

他们都工作得很好

在sinatrarb谷歌小组询问后,有人建议我将@songs=Song.all(:artist_name=>'{artist.name})改为@songs=Song.all(:artist=>{name=>@artist.name}),所以问题解决了,尽管我还不确定为什么要这样写。