使用DataMapper进行动态查询

时间:2013-11-04 20:32:13

标签: 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类:

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.

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

1 个答案:

答案 0 :(得分:0)

在sinatrarb谷歌小组询问后,我被建议改变

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

这一行:

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

或与此

@songs= @artist.songs

他们都工作正常

相关问题