如何通过SQL函数使属性设置器发送值

时间:2012-04-27 02:23:26

标签: sql ruby-on-rails postgresql activerecord arel

我正在尝试使用ActiveRecord模型中的属性设置器在rails生成其sql查询之前将其值包装在text2ltree()postgres函数中。

例如,

post.path = "1.2.3"
post.save

应生成类似

的内容
UPDATE posts SET PATH=text2ltree('1.2.3') WHERE id = 123 # or whatever

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

编辑:为了达到您正在寻找的目标,您可以使用它来覆盖模型文件中的默认设置器:

def path=(value)
  self[:path] = connection.execute("SELECT text2ltree('#{value}');")[0][0]
end

然后你上面的代码就可以了。

我有兴趣了解更多关于ActiveRecord的内部结构及其难以理解的元编程基础,所以作为练习,我试图完成您在下面的评论中描述的内容。这是一个适合我的例子(这完全在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中我仍然会使用迁移来创建查询重写规则,但这样可以带来很好的学习体验。希望它有效,我现在可以停止思考如何做到这一点。