ruby-on-rails - 没有 ActiveRecord 的 Rails Draper Gem Association 装饰
问题描述
在我的 Rails 项目中,我使用Draper gem来装饰我的对象。
从文档看来,您可以使用以下内容装饰对象的关联项目:
class AuthorDecorator < Draper::Decorator
decorates_association :articles
end
这样当AuthorDecorator
装饰一个Author
时,它也将ArticleDecorator
用于装饰关联的Articles
。
如果你定义一个Article
tobelongs_to :author
和一个Author
has_many :articles
;这一切都很好 并且 that Author
andArticle
都继承自ApplicationRecord
orActiveRecord::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)
这基本上是说我需要一张桌子。但在这种情况下,我不想要一张桌子。
我应该怎么办?
谢谢!
解决方案
推荐阅读
- angularjs - Ionic 4 cordova Googleplus 插件无法在生产中运行
- python - 如何在不需要任何权限的情况下更新 conda?
- ssh - centos docker :libssh2 握手失败
- python - Dataclasses 和 TypedDicts 之间的类型检查转换
- python-3.x - 如何从文件夹中获取最新的同名文件?
- java - 如何通过 ResponseEntity 发送 ByteArrayResource
- javascript - 在 React 中将 JSON 数据解析为 Chartjs
- .net - 如何在低级 ElasticSearch.NET 客户端的类查询中搜索类?
- python - 如何使用 Matplotlib 制作更精细的 3D 绘图
- python - 有没有办法根据列中的相似元素加入 2 个熊猫数据框?