Sinatra 中的 Ruby 使用 DataMapper 无法检索关联
由于某种原因,我的模型不包含我使用 has n 链接的关联模型。
我的定义如下:
class Post
include DataMapper::Resource
has n, :comments
property :id, Serial
property :name, String
end
class Comment
include DataMapper::Resource
belongs_to :post
property :id, Serial
property :comment, Text
end
然后由于某种原因使用以下路由/代码会引发错误,因为注释似乎不是用户的属性。
class MyApp < Sinatra::Application
get "/" do
@post = Post.get(1)
@post.comments.inspect
end
end
DataMapper 生成的表看起来很好(使用 DataMapper.finalize 和 DataMapper.auto_upgrade!)。它有一个用户表和一个评论表,该表在 posts.id 上有一个外键。
对此有什么建议吗?
For some reason my model does not contain the associated models I linked using has n.
My definition is as follows:
class Post
include DataMapper::Resource
has n, :comments
property :id, Serial
property :name, String
end
class Comment
include DataMapper::Resource
belongs_to :post
property :id, Serial
property :comment, Text
end
Then using the following route/code for some reason it throws an error because comments does not appear to be an attribute of user.
class MyApp < Sinatra::Application
get "/" do
@post = Post.get(1)
@post.comments.inspect
end
end
The tables DataMapper generate seem fine (using DataMapper.finalize & DataMapper.auto_upgrade!). It has a user table and a comment table that has a foreign key on posts.id.
Any advice on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用什么版本的数据映射器?
您可以创建评论,保存它并查看它在 post_id 中存储什么值?
尝试像这样明确地放置父键子键关系
What version of datamapper are you using?
You can create comments, save it and see what values is it storing in post_id?
Try to explicitly put the parent-key child-key relationship like this
好吧,事实证明我在注释声明中添加了一个 Time 字段,如下所示:
我也在使用 MySQL,它没有 Time 类型并将其保存为 DateTime。当尝试使用 Post.comments 检索评论时,DataMapper 尝试将其解析为时间并死亡。
希望这可以帮助大家解决一些头痛的问题。
Ok, it turns out i added a Time field to the comment declaration, like so:
I'm also using MySQL which doesn't have the Time type and saves it as DateTime. When trying to retrieve the comments using Post.comments DataMapper tries to parse it as Time and dies.
Hope this saves somebody some headaches.