将Rails模型连接到数据库视图吗? [英] Connecting a Rails model to a database view?
问题描述
我听说您可以在模型中将模型绑定到数据库视图(而不是通常的表),而这只是通过创建一个具有模型表通常具有的名称的视图而成为圆顶。 / p>
我无法使它在PostgreSQL 9的Rails 3.0.5中工作。
我有东西吗
postgresql适配器中的导轨没有出现在 pg_views
查看其模型。
您应该使用常规模型为视图命名。
您可能会产生一点骇客,例如这样来解决此问题:
#-*-编码:utf-8-*-
ActiveSupport.on_load(:active_record)做
ActiveRecord :: ConnectionAdapters :: PostgreSQLAdapter.class_eval
def table_exists?(name)
如果超级
返回true名称= name.to_s
模式,表= name.split('。',2)
除非表#A t如果没有提供模式
表=模式
模式= nil
如果name =〜/ ^ /#处理引用的表名
,则结束
table = name
schema = nil
end
query(<< -SQL).first [0] .to_i> 0
从pg_views
中选择COUNT(*)
WHERE viewname ='#{table.gsub(/(^ | $)/,'')}'
# {模式? AND schemaname ='#{schema}':''}
SQL
结束
结束
结束
将其放入文件 RAILS_ROOT / config / initializers / postgresql_view_support.rb
。
PS:
此代码适用于Rails 3.0.5。
I've heard that you can tie a model in rails to a database view (instead of a table as per usual) and that this is dome simply by creating a view with the name that the model's table would ordinarily have.
I am not getting this to work in rails 3.0.5 with PostgreSQL 9.
Is there something I am missing?
Rails in it's postgresql adapter didn't look in pg_views
view for it's models.
You should name views with some names, your normal models do.
You could create little hack, like this to solve this problem:
# -*- encoding: utf-8 -*-
ActiveSupport.on_load(:active_record) do
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
def table_exists?(name)
return true if super
name = name.to_s
schema, table = name.split('.', 2)
unless table # A table was provided without a schema
table = schema
schema = nil
end
if name =~ /^"/ # Handle quoted table names
table = name
schema = nil
end
query(<<-SQL).first[0].to_i > 0
SELECT COUNT(*)
FROM pg_views
WHERE viewname = '#{table.gsub(/(^"|"$)/,'')}'
#{schema ? "AND schemaname = '#{schema}'" : ''}
SQL
end
end
end
Place this into file RAILS_ROOT/config/initializers/postgresql_view_support.rb
.
PS:
This code is for Rails 3.0.5.
这篇关于将Rails模型连接到数据库视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!