Sinatra 中的 Ruby 使用 DataMapper 无法检索关联

发布于 2024-12-21 07:22:05 字数 657 浏览 2 评论 0原文

由于某种原因,我的模型不包含我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我很坚强 2024-12-28 07:22:05

您使用什么版本的数据映射器?

您可以创建评论,保存它并查看它在 post_id 中存储什么值?

尝试像这样明确地放置父键子键关系

belongs_to :post, :parent_key => [:id], :child_key => [:post_id]
property   :post_id, Integer

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

belongs_to :post, :parent_key => [:id], :child_key => [:post_id]
property   :post_id, Integer
冷…雨湿花 2024-12-28 07:22:05

好吧,事实证明我在注释声明中添加了一个 Time 字段,如下所示:

class Comment
    include DataMapper::Resource

    belongs_to :post

    property :id, Serial
    property :time, Time
    property :comment, Text  
end

我也在使用 MySQL,它没有 Time 类型并将其保存为 DateTime。当尝试使用 Post.comments 检索评论时,DataMapper 尝试将其解析为时间并死亡。

希望这可以帮助大家解决一些头痛的问题。

Ok, it turns out i added a Time field to the comment declaration, like so:

class Comment
    include DataMapper::Resource

    belongs_to :post

    property :id, Serial
    property :time, Time
    property :comment, Text  
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文