【发布时间】: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