我试图扩展我在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"
答案 0 :(得分:0)
事实证明这一切都发生了,因为DataMapper希望用户给Artist属性赋值,这也是我在slim文件中没有做的事情。我想这就是id属性保持nil值的原因,我得到404错误。