编辑:要完全实现您在上面寻找的内容,您可以使用它来覆盖模型文件中的默认设置器:
def path=(value)
self[:path] = connection.execute("SELECT text2ltree('#{value}');")[0][0]
end
那么你上面的代码就可以了。
我有兴趣更多地了解 ActiveRecord 的内部结构及其难以理解的元编程基础,因此作为练习,我尝试完成您在下面的 cmets 中描述的内容。这是一个对我有用的例子(这都在 post.rb 中):
module DatabaseTransformation
extend ActiveSupport::Concern
module ClassMethods
def transformed_by_database(transformed_attributes = {})
transformed_attributes.each do |attr_name, transformation|
define_method("#{attr_name}=") do |argument|
transformed_value = connection.execute("SELECT #{transformation}('#{argument}');")[0][0]
write_attribute(attr_name, transformed_value)
end
end
end
end
end
class Post < ActiveRecord::Base
attr_accessible :name, :path, :version
include DatabaseTransformation
transformed_by_database :name => "length"
end
控制台输出:
1.9.3p194 :001 > p = Post.new(:name => "foo")
(0.3ms) SELECT length('foo');
=> #<Post id: nil, name: 3, path: nil, version: nil, created_at: nil, updated_at: nil>
在现实生活中,我假设您希望 include ActiveRecord::Base 中的模块,在加载路径中较早的某个文件中。您还必须正确处理传递给数据库函数的参数类型。最后,我了解到connection.execute 是由每个数据库适配器实现的,因此在 Postgres 中访问结果的方式可能会有所不同(此示例是 SQLite3,其中结果集以哈希数组的形式返回,第一个的键数据记录为0]。
这篇博文非常有用:
http://www.fakingfantastic.com/2010/09/20/concerning-yourself-with-active-support-concern/
就像 Rails 插件创作指南一样:
http://guides.rubyonrails.org/plugins.html
另外,对于它的价值,我认为在 Postgres 中我仍然会使用迁移来创建查询重写规则,但这带来了很好的学习体验。希望它有效,我现在可以停止思考如何去做。