【问题标题】:ActiveRecord::StatementInvalid in Controller when using an ActiveRecord with a table name and a postgresql view使用带有表名和 postgresql 视图的 ActiveRecord 时,Controller 中的 ActiveRecord::StatementInvalid
【发布时间】:2017-05-21 15:06:22
【问题描述】:

我有一个属于重复的事​​件,我试图在显示事件时显示重复标题。但我不想要两个这样的数据库调用

@event.Repeat.title

我使用下面的迁移创建了一个 postgresql 视图

class EventWithRepeat < ActiveRecord::Migration[5.1]
  def up
    self.connection.execute %Q( create view event_with_repeat as
                                Select events.*, repeats.title as RepeatTitle from Events
                                inner join repeats on events.repeat_id = repeats.id; )
  end

  def down
    self.connection.execute %Q( drop view event_with_repeat; )
  end

end

问题肯定出在上面的迁移上。我似乎不能只运行那个迁移。执行 rake db:migrate 不会做任何事情。 rake db:migrate:down with the version 会导致错误,因为关系不存在,因此无法删除它。

直接在数据库中创建 SQL 视图确实有效,但我的迁移似乎没有执行。我正在使用 Rails 5。

这是我的 ActiveRecord 类

class EventRepeat < ActiveRecord::Base
  self.table_name = "event_with_repeat"
  self.primary_key = "id"

  def readonly?
    true
  end
end

这是我的控制器类中的方法

def show
    @event = EventRepeat.find(params[:id])
end

我运行了迁移,我可以在 psql 中查看视图,因此该视图存在。我确实做了 db:reset 但没有帮助。

错误消息表明问题出在此 SQL 上

SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"event_with_repeat"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum

错误信息是

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  relation "event_with_repeat" does not exist

但视图 event_with_repeat 确实存在。

我有这个想法

<%= @event.RepeatTitle %>

关于如何修复此错误以及代码有什么问题的任何想法?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    我通过删除迁移并重新创建它来解决此问题。但是,如果我执行 rake db:reset,我会再次遇到同样的问题。此命令创建表但不创建 postgresql 视图,并且它看起来不像正在执行最后一次迁移。我必须删除迁移并重新创建它才能使其正常工作。

    此迁移似乎只运行一次?

    创建迁移的顺序

    1. 20170515163011_create_events
    2. 20170520203458_create_repeats
    3. 20170520203852_add_repeat_to_event
    4. 20170521190734_event_with_repeat

    我将架构格式更改为 :sql config.active_record.schema_format :sql in application.rb

    将架构转储到 structure.sql 确实有效,但再次运行 rake db:reset 不会创建视图。我总是必须删除迁移并重新创建它。

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多