我正在尝试扩展我在 sinatra 书中看到的一个示例。我想尝试使用 DataMapper,所以我最终得到了这个:
require 'dm-core'
require 'dm-migrations'
require 'rubygems'
require 'sinatra'
configure:development do
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/3sbase.db")
DataMapper.auto_upgrade!
end
class Artist
include DataMapper::Resource
property :name, String, :key=>true
property :born, Integer
has n, :songs
end
class Song
include DataMapper::Resource
property :id, Serial
property :title, String
property :year, Integer
property :singer, String
belongs_to :artist
end
DataMapper.finalize
get '/songs' do
@songs = Song.all
slim :songs
end
get '/songs/new' do
@song = Song.new
slim :new_song
end
get '/songs/:id' do
@song = Song.get(params[:id])
slim :show_songs
end
post '/songs' do
song = Song.create(params[:song])
redirect to("/songs/#{song.id}")
end
get '/songs/:id/edit' do
@song = Song.get(params[:id])
slim :edit_song
end
put '/songs/:id' do
song = Song.get(params[:id])
song.update(params[:song])
redirect to("/songs/#{song.id}")
end
delete '/songs/:id' do
Song.get(params[:id]).destroy
redirect to('/songs')
end
问题是,当我尝试向空数据库创建一首新歌曲时,在我提供歌曲的详细信息并按保存按钮后出现 404 错误。新页面的链接不采用 /:id 扩展名应该。我实际上只更改了 DataMapper 的类,添加了“DataMapper.auto_upgrade!” 并根据新的类属性更改了 slim 文件。原来是:
configure:development do
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")
end
class Song
include DataMapper::Resource
property :id, Serial
property :title, String
property :lyrics, Text
property :length, Integer
property :released_on, Date
def released_on=date
super Date.strptime(date, '%m/%d/%Y')
end
end
DataMapper.finalize
我怀疑我在 DataMapper 的课程工作方式上遗漏了一些东西。欢迎任何关于我可能做错的想法。
我目前使用的苗条文件是
#new_song.slim
h1 Add A New Song
form method="POST" action="/songs"
== slim :song_form
#song_form.slim
label for="title" Title:
input#title type="text" name="song[title]" value="#{@song.title}"
label for="year" Released on:
input#year type="text" name="song[year]" value="#{@song.year}"
label for="singer" Performed by:
input#singer type="text" name="song[singer]" value="#{@song.singer}"
input type="submit" value="Save Song"
/show_songs.slim
h1= @song.title
p Release Date: #{@song.year}
p <a href="/songs">back to songs index</a>
p <a href="/songs/#{@song.id}/edit">edit this song</a>
form action="/songs/#{@song.id}" method="POST"
input type="hidden" name="_method" value="DELETE"
input type="submit" value="delete this song"