Using active record and mysql on ruby script

2019-08-12 19:47发布

问题:

I've been trying to use mysql and active record on a ruby script but I'm getting the following message: Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'. Or use gem 'mysql2' (RuntimeError). Before I was getting a message about gem 'mysql2' missing but then i checked the source code on the connection adapters in active record and saw that it require mysql gem which i didnt have installed.

this is my script:

require 'rubygems'
require 'active_record'
require 'mechanize'
require 'nokogiri'
require 'active_record'
require 'mysql2'
gem 'mysql2'

ActiveRecord::Base.establish_connection ({
  :adapter => "mysql",
  :host => "localhost",
  :username => "root",
  :password => "",
  :database => "rainalytics"})

ActiveRecord::Schema.define(:version => 20110320035328) do

    create_table "score_logs", :force => true do |t|
      t.integer  "blog_posts"
      t.integer  "featured"
    end

    create_table "users", :force => true do |t|
      t.datetime "created_at"
      t.datetime "updated_at"
    end

  end


    class User < ActiveRecord::Base
      has_many :score_logs
    end
    class ScoreLog < ActiveRecord::Base
      belongs_to :user
  end

回答1:

Im not using the 'require 'mysql2' or 'gem 'mysql2' parts, and it seems to be working fine, I also have additional {} inside the ActiveRecord::Base block

hope this can help someone in future :)

This is what I use
ruby 1.9.2p318 (2012-02-14 revision 34678) [x86_64-darwin11.2.0]
Rails 3.1.0


require "rubygems"
require "active_record"

ActiveRecord::Base.establish_connection ({
  :adapter => "mysql2",
  :host => "localhost",
  :username => "root",
  :password => "root",
  :database => "cybercellar"})

class Zone < ActiveRecord::Base

end

zone = Zone.all
print zone

then I navigate to my app folder and run the file

ruby script/test.rb