通过 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 数据?
谢谢你!
I have following model:
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
My full code looks like
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
Am I thinking wrong? how to do it correctly?
Can you provide me some working example?
How I can process JSON data which I want to post?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个创建无法按编写的那样工作,因为您没有名为“name”的变量。也许您的意思是
b.name = jdata
?它适用于具有有效名称属性的我,并且对
create
的调用也可以正常工作:您需要分享更多详细信息,以便我们重现您的问题,然后我们才能提供帮助。另请注意,您的代码包含一些转移注意力的内容,我在上面添加这些内容只是为了完整性。 Player 表、模型、关系和 JSON 序列化都不会影响我的测试用例。代码也可以是:
Your first creation doesn't work as written because you have no variable named "name". Perhaps you meant
b.name = jdata
?It works for me with a valid name attribute, and the call to
create
works fine as well:You'll need to share more details for us to reproduce your problem before we can help. Also note that your code includes some red herrings, which I've included above just for completeness. The Player table, model, relationships, and JSON serialization all do not affect my test case. The code could just as well be: