【发布时间】:2015-07-26 02:36:59
【问题描述】:
我想在我正在编写的 Ruby gem 中使用数据库。该 gem 旨在用于 Rails 应用程序,并将包含从 Rails 主应用程序传入的文档的倒排索引。
我对如何处理这件事有点困惑。我应该以某种方式连接到主 Rails 数据库吗?或者我应该有一个独立的数据库?理想情况下,我只想使用 ActiveRecord 来创建、更新、删除和查询条目,但我不确定如何设置。
此时数据将进入数据库:
module ActiveRecordExtension
extend ActiveSupport::Concern
class_methods do
def foo
"bar"
end
end
included do
after_save :add_to_inverted_index
end
def add_to_inverted_index
# This is where I'd take the fields from the Rails app
# and include them to my inverted index. However, I'm struggling
# to find a way to hook into a database from my gem to do this.
end
end
# Include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension)
非常感谢您的建议!谢谢
【问题讨论】:
-
您需要用户告诉您的 gem,他想在您的 gem 中“注入”/使用的模型是什么。你可以通过多种方式让他这样做,从函数到参数、配置文件等等……
-
是的,我已经收到要“注入”的模型,只要用户执行
class Model < ActiveRecord::Base; require 'mygem'; end之类的操作。我的问题更多的是,一旦我从模型中收到数据,我如何将它从我的 gem 中添加到数据库中?
标签: ruby-on-rails gem