【问题标题】:how to require active record working outside of rails如何要求在 Rails 之外工作的活动记录
【发布时间】:2011-04-09 08:38:12
【问题描述】:

我需要主动记录,但我在 Rails 之外工作(原因如下:Simple Ruby Input Validation Library)。我需要整个 rails gem,还是可以做 DRYer?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rubygems require


    【解决方案1】:

    这是我在 Rails 之外使用 ActiveRecord 的方式:

    #!/usr/bin/ruby
    
    require 'active_record'
    require 'mysql2' # or 'pg' or 'sqlite3'
    
    ActiveRecord::Base.establish_connection(
      adapter:  'mysql2', # or 'postgresql' or 'sqlite3'
      database: 'DB_NAME',
      username: 'DB_USER',
      password: 'DB_PASS',
      host:     'localhost'
    )
    
    # Note that the corresponding table is 'orders'
    class Order < ActiveRecord::Base
    end
    
    Order.all.each do |o|
      puts "o: #{o.inspect}"
    end
    

    【讨论】:

    • 你需要指定mysql2作为适配器,而不是mysql(对于googlers)。
    • 你还需要 ubuntu 上的 libmysqlclient-dev(可能还有其他平台)
    • @BenWest libmysqlclient-dev有什么用? (对于我缺乏这方面的基本知识,我深表歉意)
    • @Renan 因为 ruby​​ gem 编译它的一些依赖项,它需要它的依赖项链接到的库的开发头文件。 cprogramming.com/compilingandlinking.html
    • 我希望人们不要直接引用 Ubuntu/Debian 软件包名称。他们的命名约定充其量是奇怪的,这会导致令人困惑的答案被投票,这最终无助于人们搜索。
    【解决方案2】:
    require 'rubygems'
    require 'active_record'
    

    【讨论】:

    • Ruby 1.9 假定require 'rubygems'
    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多