ruby中的POST方法不会将数据插入表中

时间:2016-01-02 15:45:43

标签: ruby sinatra

我刚开始学习编程。我读Darren Johnson的书“Jump start Sinatra”。 我按照书中的说明做了一切,但是在表格中插入一个新条目并不起作用。我点击“保存歌曲”按钮但没有任何反应。 同时修改现有的记录。

我的main.rb

require 'sinatra'
require 'sinatra/reloader' if development?
require 'slim'
require 'sass'
require './song'

set :public_folder, 'public'
set :views, 'views'

 get('/styles.css'){ scss :styles }
 get '/' do
        slim :home
 end

  get '/about' do
        @title = "All About This Website"
        slim :about
  end

  get '/contact' do
        slim :contact
  end

  not_found do
        slim :not_found
  end

我的歌.rb

require 'dm-core'
require 'dm-migrations'

configure 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

 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_song
 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

我的观点/ song_form.slim

label for="title" Title:
input#title type="text" name="song[title]" value="#{@song.title}"
label for="length" Length:
input#length type="number" name="song[length]" value="#{@song.length}"
label for="released_on" Date(mm/dd/yyyy):
input#released_on type="text" name="song[released_on]" value="#{@song.released_on.strftime("%m/%d/%Y") if @song.released_on}"
label for="lyrics" Lyrics:
textarea#lyrics name="song[lyrics]" == @song.lyrics
input type="submit" value="Save Song"

我的观点/ edit_song.slim

h1 Edit Song
form method="POST" action="/songs/#{@song.id}"
  input type="hidden" name="_method" value="PUT"
  == slim :song_form

当我尝试在IRB中添加新表记录时:

irb(main):001:0> require './song'
NoMethodError: undefined method `get' for main:Object
from /media/kamrenov/other/work/sinatra/song.rb:21:in `<top (required)>'
from /home/kamrenov/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/kamrenov/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from (irb):1
from /home/kamrenov/.rbenv/versions/2.2.1/bin/irb:11:in `<main>'

0 个答案:

没有答案