通过Sinatra在续集中创造新纪录

时间:2011-01-18 17:41:21

标签: ruby sinatra sequel

我有以下型号:

DB.create_table :teams do  
  primary_key :id
  column :name, :text, :unique=>true
end

DB.create_table :players do  
  primary_key :id
  column :name, :text, :unique=>true
  column :position, :text
  foreign_key :team_id
end

class Team < Sequel::Model
    plugin :json_serializer
    one_to_many :players
end

class Player < Sequel::Model
    plugin :serialization, :json
    many_to_one :teams
end

我的完整代码看起来像

require 'rubygems'
require 'sequel'
require 'sinatra'
require 'db' #model file
require 'thread'
require 'json'
require "sinatra/reloader" if development?  # reload

before do
  @teams = Team.all
end

get '/teams/:id' do |id|
  @team = Team[id]
  haml :team_view
end

post '/teams/?' do 
    Team.create(:name => 'FC Barcelona') 
#here: Read error: #<NoMethodError: undefined method `bytesize' for [:name, "FC Barcelona"]:Array>

end

我错了吗?怎么做得对? 你能给我一些工作实例吗? 我如何处理我想发布的JSON数据?

谢谢!

1 个答案:

答案 0 :(得分:2)

您的第一个创建无法正常编写,因为您没有名为“name”的变量。也许你的意思是b.name = jdata

它适用于我有效的名称属性,对create的调用也可以正常工作:

require 'sequel'
p Sequel::VERSION #=> "3.15.0"

DB = Sequel.sqlite

DB.create_table :teams do  
  primary_key :id
  column :name, :text, :unique=>true
end

DB.create_table :players do  
  primary_key :id
  column :name, :text, :unique=>true
  column :position, :text
  foreign_key :team_id
end

class Team < Sequel::Model
  plugin :json_serializer
  one_to_many :players
end

class Player < Sequel::Model
  plugin :serialization, :json
  many_to_one :teams
end

begin
  Team.new do |b|
    b.name = name
    b.save
  end
rescue Exception=>e
  p e
  #=> #<NameError: undefined local variable or method `name' for main:Object>
end

Team.new do |b|
  b.name = "Boo!"
  b.save
end
Team.create(:name => 'FC Barcelona')

p Team.all
# [
#  #<Team @values={:id=>1, :name=>"Boo!"}>,
#  #<Team @values={:id=>2, :name=>"FC Barcelona"}>
# ]

在我们提供帮助之前,您需要与我们分享更多详细信息才能重现您的问题。另请注意,您的代码中包含一些红色鲱鱼,为了完整起见,我将其包含在上面。 Player表,模型,关系和JSON序列化都不会影响我的测试用例。代码也可以是:

require 'sequel'
DB = Sequel.sqlite
DB.create_table :teams do  
  primary_key :id
  column :name, :text, :unique=>true
end
class Team < Sequel::Model; end
Team.create(:name => 'FC Barcelona')
p Team.all