Ruby/Sinatra/DataMapper多对多如何创建对象
我有两个类叫做User和Gig,还有一个连接表UsergigRuby/Sinatra/DataMapper多对多如何创建对象,ruby,many-to-many,sinatra,datamapper,Ruby,Many To Many,Sinatra,Datamapper,我有两个类叫做User和Gig,还有一个连接表Usergig class Usergig include DataMapper::Resource property :id, Serial belongs_to :user belongs_to :gig end class Gig include DataMapper::Resource property :id, Serial property :gigname, Str
class Usergig
include DataMapper::Resource
property :id, Serial
belongs_to :user
belongs_to :gig
end
class Gig
include DataMapper::Resource
property :id, Serial
property :gigname, String
property :gigtext, Text
has n, :usergigs
has n, :users, :through => :usergigs
end
class User
include DataMapper::Resource
property :id, Serial
property :username, String
property :realname, String
has n, :usergigs
has n, :gigs, :through => :usergigs
end
当我尝试跑步时:
post '/gig/add' do
user = User.get(1)
gig = user.gigs.create(:gigname => params[:gig_gigname], :gigtext => params[:gig_gigtext])
end
我得到一个错误:
在/gig/add处的命名错误
nil:NilClass的未定义方法“include”
我已经在谷歌上搜索了大约两个小时,阅读了DataMapper文档。
有人知道我做错了什么吗?在Usergig中尝试以下操作:
belongs_to :user, :key => true
belongs_to :gig, :key => true
您忘记调用DataMapper.finalize…这是您在加载所有模型后需要调用的。Rails为您做这件事,在Sinatra中,您必须手动调用它。我编辑了您的文章,使其可读。你应该粘贴你的代码(没有行号,所以我们也可以复制/粘贴!),然后选择它并按CMD+K(Mac)或ctrl+K(PC)。你试过
:through=>Usergig
?啊,谢谢!这是我的第一篇帖子,我还在学习:-)顺便说一句,它现在运行良好。似乎也忘记了使用DataMapper.finalize。非常感谢!!:-)