首页 > 解决方案 > 没有 ActiveRecord 的 Rails Draper Gem Association 装饰

问题描述

在我的 Rails 项目中,我使用Draper gem来装饰我的对象。

从文档看来,您可以使用以下内容装饰对象的关联项目:

class AuthorDecorator < Draper::Decorator
  decorates_association :articles
end

这样当AuthorDecorator装饰一个Author时,它也将ArticleDecorator用于装饰关联的Articles

如果你定义一个Articletobelongs_to :author和一个Author has_many :articles;这一切都很好 并且 that AuthorandArticle都继承自ApplicationRecordorActiveRecord::Base并且您有一个带有authors表和articles表的数据库。

但是,在我的具体情况下,我的 API 服务只进行一些弹性搜索,然后执行一些计算和格式化,然后将搜索结果呈现给用户。所以没有必要为这些“计算和格式化的结果”创建一个数据库,我绝对不想为这些结果创建一个数据库。

我可能有一个模型,说:

class Author
  attr_reader :name, :articles

  def initialize(params: {})
    @name = params['name']
  end

  def id
    name
  end
end

很简单。例如Author.new(params: {'name'=> 'John'}会给我一个 id 和名称为“John”的作者。

然后是一个Ariticle模型

class Article
  attr_reader :text

  def initialize(params: {})
    @text = params['text']
  end

  def id
    text
  end
end

假设,假设我所有的文章文本和用户名都是唯一的,并且从不重复。

现在让我们创建一个作者和一些文章:

author = Author.new(params: {'name'=>'John'})
art_1 = Aritcle.new(params: {'text'=>'text 1'})
art_2 = Aritcle.new(params: {'text'=>'text 2'})
author.articles = [art_1, art_2]

现在我打电话AuthorDecorator.decorate(author),它根本不会打电话ArticleDecorator。我认为那是因为我没有has_many :articles在我的Author模型和belongs_to :author我的Article模型中添加。但我做不到。因为如果我这样做了,我会得到一个错误

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  relation "articless" does not exist)

这基本上是说我需要一张桌子。但在这种情况下,我不想要一张桌子。

我应该怎么办?

谢谢!

标签: ruby-on-railsrubyactiverecorddecoratordraper

解决方案


推荐阅读