繁体   English   中英

如何在Rails项目之外访问active_record数据库

[英]How to access active_record database outside of rails project

我正在使用没有Rails项目的active_record数据库。

require 'active_record'

ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "posts.db")

unless File.exists? "posts.db"
  ActiveRecord::Schema.define do
    create_table :posts do |t|
      t.column :title, :string
      t.column :content, :text
    end
  end
end

class Post < ActiveRecord::Base
  def do_something
    # do_something
    create(title: title, content: content)
  end
end

现在,我正在使用Firefox附加SQL Lite Manager来访问数据库。 但是,如果可能的话,我想像rails console这样访问数据库。

即使仅使用active_record也可以使用rails console吗?

您可以安装宝石。
然后在当前项目目录中添加.pryrc
在您的.pryrc中,您可以添加以下内容:

current_dir = Dir.pwd
$LOAD_PATH.unshift(current_dir)

现在,每次您进入撬会话时,只需手动要求您的文件即可,例如:

pry(main)> require 'models/post'

这是最简单的方法,您可以从此处自定义或扩展。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM