【问题标题】:Ruby on Rails - How to relate a comment model to a blog with no databaseRuby on Rails - 如何将评论模型与没有数据库的博客相关联
【发布时间】:2012-05-28 05:49:12
【问题描述】:

我正在使用 gem postmarkdown 在 RoR 中创建博客。 gem 中的 Post 模型不受数据库支持(它使用 ActiveModel)。对于不使用数据库来存储博客文章的博客,我将如何将 Comment 模型与 Post 模型相关联?

例如,对于一个由 ActiveRecord 数据库支持的典型博客,我可以设置关系(例如)

class Post < ActiveRecord::Base
has_many :comments

但是,在这种情况下,我不知道创建评论模型的最佳方式。

【问题讨论】:

    标签: ruby-on-rails database ruby-on-rails-3 activerecord activemodel


    【解决方案1】:

    如果 Post 是一个 activemodel,则不能使用 activerecord 中的方法设置关系。您可以在github 查看自述文件。它没有那个功能。

    一种方法是简单地在 Post 模型中定义自己的方法。

    class Post
      def comments
        Comment.where(:post_id => id)
      end
    end
    
    class Comment < ActiveRecord::Base
      def post
        Post.find_by_id(post_id)
      end
    end
    

    编辑: 啊,我刚找到一个类似的问题,Ruby on Rails 3 (3.1) ActiveModel Associations (tableless nested models)。你也可以去看看。

    【讨论】:

    • 感谢您的回复(抱歉回复晚了)。在这种情况下,我应该如何处理我的 routes.rb? cmets 资源是帖子中的嵌套资源吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多