gpt4 book ai didi

ruby-on-rails - 将 Rails 模型连接到数据库 View ?

转载 作者:行者123 更新时间:2023-11-29 11:23:55 26 4
gpt4 key购买 nike

我听说您可以将 rails 中的模型绑定(bind)到数据库 View (而不是像往常一样的表),并且只需创建一个具有模型表通常具有的名称的 View 即可。

我没有让它在 PostgreSQL 9 的 Rails 3.0.5 中工作。

有什么我想念的吗?

最佳答案

它的 postgresql 适配器中的 Rails 没有在 pg_views View 中查找它的模型。

你应该用一些名字来命名 View ,你的普通模型就是这样。

你可以像这样创建小技巧来解决这个问题:

# -*- 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

将其放入文件 RAILS_ROOT/config/initializers/postgresql_view_support.rb

附言:

此代码适用于 Rails 3.0.5。

关于ruby-on-rails - 将 Rails 模型连接到数据库 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5494779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com