【问题标题】:In Rails model, can we not save an item if the table doesn't exist?在 Rails 模型中,如果表不存在,我们可以不保存项目吗?
【发布时间】:2015-08-05 11:10:33
【问题描述】:

我有几个使用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 表。我收到一条错误消息,提示 LogTable 不存在。如何防止此错误,如果特定数据库中不存在该表,是否有方法中止保存?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord callback


    【解决方案1】:

    您可以通过以下方式检查表是否存在

    ActiveRecord::Base.connection.table_exists? 'log_table'
    

    回调可以这样修改

    after_save :record_to_log, :if => ActiveRecord::Base.connection.table_exists?('log_table')
    

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 2023-04-08
      • 1970-01-01
      • 2014-05-06
      • 2019-12-28
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      相关资源
      最近更新 更多