2009-10-29 14 views

答えて

84
require 'active_record' 

# Change the following to reflect your database settings 
ActiveRecord::Base.establish_connection(
    adapter: 'mysql2', # or 'postgresql' or 'sqlite3' or 'oracle_enhanced' 
    host:  'localhost', 
    database: 'your_database', 
    username: 'your_username', 
    password: 'your_password' 
) 

# Define your classes based on the database, as always 
class SomeClass < ActiveRecord::Base 
    #blah, blah, blah 
end 

# Now do stuff with it 
puts SomeClass.find :all 
some_class = SomeClass.new 
+0

未定義のメソッド 'require_gem」 - あなたは宝石 "のActiveRecordを" 意味ですか? –

+2

require_gem呼び出しは非推奨です。今は "activerecord"が必要です。 – kafuchau

+0

@kchau:ああ、ありがとう。私はかなりの時間にそれを使用していません。 – Pesto

10

それはActiveRecordの(V3の+)のそれ以降のバージョンでは、あなたがそう

require "active_record" 
7

あなたはわずか数で、インメモリのSQLiteデータベースとの最小限のスクリプトを作成することができますようにそれを必要とする必要があることは注目に値しますライン。この回答もavailable as a Gistです。

Jon Leighton's blog postに感謝して、素晴らしいActiveRecordのバグレポートを投稿する方法について説明します。


# Based on http://www.jonathanleighton.com/articles/2011/awesome-active-record-bug-reports/ 

# Run this script with `$ ruby my_script.rb` 
require 'sqlite3' 
require 'active_record' 

# Use `binding.pry` anywhere in this script for easy debugging 
require 'pry' 

# Connect to an in-memory sqlite3 database 
ActiveRecord::Base.establish_connection(
    adapter: 'sqlite3', 
    database: ':memory:' 
) 

# Define a minimal database schema 
ActiveRecord::Schema.define do 
    create_table :shows, force: true do |t| 
    t.string :name 
    end 

    create_table :episodes, force: true do |t| 
    t.string :name 
    t.belongs_to :show, index: true 
    end 
end 

# Define the models 
class Show < ActiveRecord::Base 
    has_many :episodes, inverse_of: :show 
end 

class Episode < ActiveRecord::Base 
    belongs_to :show, inverse_of: :episodes, required: true 
end 

# Create a few records... 
show = Show.create!(name: 'Big Bang Theory') 

first_episode = show.episodes.create!(name: 'Pilot') 
second_episode = show.episodes.create!(name: 'The Big Bran Hypothesis') 

episode_names = show.episodes.pluck(:name) 

puts "#{show.name} has #{show.episodes.size} episodes named #{episode_names.join(', ')}." 
# => Big Bang Theory has 2 episodes named Pilot, The Big Bran Hypothesis. 

# Use `binding.pry` here to experiment with this setup. 
関連する問題