【问题标题】:using sqlite3 with ruby将 sqlite3 与红宝石一起使用
【发布时间】:2015-09-07 08:48:07
【问题描述】:

我正在使用带有 Ruby 和 ActiveRecord 的 sqlite3。我可以看到数据库日志生成了 SQL 语句,并且我看到了数据库日志文件正在生成 - 但是,我无法找到表(.database 仅将 main 和 temp 显示为数据库)。

Ruby 连接信息

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3',
  :host => "localhost",
  :database => 'test1.db'
)

管理模型和 ActiveRecord 部分

ActiveRecord::Schema.define do
  unless ActiveRecord::Base.connection.tables.include? 'admins'
    create_table :admins do |table|
      table.column :email,     :string
      table.column :name, :string
    end
  end
end


class Admin < ActiveRecord::Base
    validates :email, presence: true, uniqueness: true
    validates :name, presence: true
    has_many :bills
end

对我可能做错了什么有什么想法吗?在上述情况下,我认为我没有选择内存数据库。

【问题讨论】:

  • 您检查了db 目录并没有发现任何内容吗?
  • db 文件的大小不是 0 - 正如我之前所说,当我输入“.database”时,它会显示 main 和 temp,但我找不到我的 admins 表
  • 你是如何创建表的,你是运行迁移还是直接尝试更新架构来检查
  • 试图启动 RoR 并且很可能没有那么知识渊博。我创建了一个迁移,运行 rake db:migrate 但用于账单模型。我只是在 irb 中运行了包含 ActiveRecord Schema 部分供管理员使用的主 ruby​​ 文件 - 那不会创建表吗?
  • 标题有点模糊。 OP还提到在另一条评论中不使用rails,但使用RoR标签。考虑编辑问题?

标签: ruby-on-rails ruby activerecord sqlite


【解决方案1】:

首先,确保在执行任何其他操作之前在控制台中运行 rake db:migrate。那应该创建表。您不会看到包含表格的单独文件,其中所有表格都在test1.db 中。我推荐使用.sqlite3 扩展,所以使用test1.sqlite3

另外,我建议您使用config/database.yml 配置您的数据库,而不是使用 ActiveRecord 手动建立连接。

也就是说,尝试从你的 shell 启动你的 rails dbconsole 并运行 .tables

rails dbconsole
sqlite3>.tables

如果你不能让它工作,使用你的rails console,并检查你的模型,看看它们是否可以访问数据库:

rails c
Admin.create(email: "test@example.com", name: "Test from Console")
Admin.all
=> # Should return the test entry

这应该可以让您与表格互动并阅读表格。每个表没有单独的文件。

【讨论】:

  • 忘了说我没有使用 rails - sinatra with activerecord
猜你喜欢
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多