【问题标题】:Ruby in Sinatra using DataMapper not retrieving associationsSinatra 中的 Ruby 使用 DataMapper 不检索关联
【发布时间】:2011-12-14 12:47:00
【问题描述】:

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

然后由于某种原因使用以下路由/代码会引发错误,因为 cmets 似乎不是用户的属性。

class MyApp < Sinatra::Application
  get "/" do

    @post = Post.get(1)    
    @post.comments.inspect
  end
end

DataMapper 生成的表看起来不错(使用 DataMapper.finalize 和 DataMapper.auto_upgrade!)。它有一个用户表和一个在posts.id 上有一个外键的评论表。

对此有何建议?

【问题讨论】:

    标签: ruby sinatra ruby-datamapper


    【解决方案1】:

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

    您可以创建 cmets,将其保存,然后查看它在 post_id 中存储了哪些值?

    尝试像这样显式放置父键子键关系

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

    【讨论】:

    • 1.2.当我创建评论时, post_id 是必需的,因此我必须在创建评论时填写它。此外,当我将评论模型更改为您的建议时,它不起作用。
    • 将属性时间设为明确的 DateTime 看看会发生什么
    【解决方案2】:

    好的,原来我在评论声明中添加了一个时间字段,如下所示:

    class Comment
        include DataMapper::Resource
    
        belongs_to :post
    
        property :id, Serial
        property :time, Time
        property :comment, Text  
    end
    

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

    希望这可以避免一些人头疼。

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      相关资源
      最近更新 更多