在Rails模型中,如果table不存在,我们是否可以不保存一个项目?
In Rails model, can we not save an item if the table doesn't exist?
我有几个使用 Records
模型的数据库。在此模型的 after_save
回调中,我在 LogTable
中创建了一个新行。我有类似的东西:
class Records < ActiveRecord::Base
after_save :record_to_log
def record_to_log
new_log = LogTable.new
new_log.keyword = "keyword"
new_log.save
end
end
但并非我所有的数据库都有 LogTable
table。我收到一条错误消息,指出 LogTable
不存在。我如何防止此错误,如果 table 在特定数据库中不存在,有没有办法中止保存?
您可以通过
检查table是否存在
ActiveRecord::Base.connection.table_exists? 'log_table'
回调可以这样修改
after_save :record_to_log, :if => ActiveRecord::Base.connection.table_exists?('log_table')
我有几个使用 Records
模型的数据库。在此模型的 after_save
回调中,我在 LogTable
中创建了一个新行。我有类似的东西:
class Records < ActiveRecord::Base
after_save :record_to_log
def record_to_log
new_log = LogTable.new
new_log.keyword = "keyword"
new_log.save
end
end
但并非我所有的数据库都有 LogTable
table。我收到一条错误消息,指出 LogTable
不存在。我如何防止此错误,如果 table 在特定数据库中不存在,有没有办法中止保存?
您可以通过
检查table是否存在ActiveRecord::Base.connection.table_exists? 'log_table'
回调可以这样修改
after_save :record_to_log, :if => ActiveRecord::Base.connection.table_exists?('log_table')