Ruby on rails 将Rails模型连接到数据库视图?

Ruby on rails 将Rails模型连接到数据库视图?,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,我听说可以将rails中的模型绑定到数据库视图(而不是通常的表),只需创建一个具有模型表通常名称的视图即可 我无法在rails 3.0.5和PostgreSQL 9中实现这一点 有什么我遗漏的吗?我猜可能与复数有关。但是如果没有更多的信息,这是很困难的。您创建的视图需要是模型的复数形式 例如 模型应该称为书 或者你可以在配置/屈折中设置一个自定义的、不可数的复数。rb它的postgresql适配器中的Rails没有在PGU视图中查看它的模型 您应该使用一些名称来命名视图,而您的普通模型会这样做

我听说可以将rails中的模型绑定到数据库视图(而不是通常的表),只需创建一个具有模型表通常名称的视图即可

我无法在rails 3.0.5和PostgreSQL 9中实现这一点


有什么我遗漏的吗?

我猜可能与复数有关。但是如果没有更多的信息,这是很困难的。您创建的视图需要是模型的复数形式

例如

模型应该称为书


或者你可以在配置/屈折中设置一个自定义的、不可数的复数。rb

它的postgresql适配器中的Rails没有在
PGU视图中查看它的模型

您应该使用一些名称来命名视图,而您的普通模型会这样做

你可以创建一个小黑客来解决这个问题:

# -*- 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
#-*-编码:utf-8-*-
ActiveSupport.on_load(:active_record)do
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
def表_存在?(名称)
如果为super,则返回true
name=name.to_s
架构,table=name.split('.',2)
除非表#,否则提供的表没有架构
表=模式
schema=nil
结束
如果name=~/^”/#处理带引号的表名
表=名称
schema=nil
结束

查询(什么是“我不能让它工作”意思?错误?错误是:表'model_name_in_pollular'不存在。不过,Viacheslav Molokov的解决方案是有效的。我曾经尝试过,在另一个应用程序中对我有效,但现在不行。不确定这是3.0.5古怪还是什么。谢谢你的帮助。
# -*- 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