Advertisement
Guest User

Untitled

a guest
Mar 8th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. require 'active_record'
  2. require 'mysql2' # or 'pg' or 'sqlite3'
  3.  
  4. # Change the following to reflect your database settings
  5. ActiveRecord::Base.establish_connection(
  6. adapter: 'mysql2', # or 'postgresql' or 'sqlite3'
  7. host: 'localhost',
  8. database: 'your_database',
  9. username: 'your_username',
  10. password: 'your_password'
  11. )
  12.  
  13. # Define your classes based on the database, as always
  14. class SomeClass < ActiveRecord::Base
  15. #blah, blah, blah
  16. end
  17.  
  18. # Now do stuff with it
  19. puts SomeClass.find :all
  20. some_class = SomeClass.new
  21.  
  22. require "active_record"
  23.  
  24. # Based on http://www.jonathanleighton.com/articles/2011/awesome-active-record-bug-reports/
  25.  
  26. # Run this script with `$ ruby my_script.rb`
  27. require 'sqlite3'
  28. require 'active_record'
  29.  
  30. # Use `binding.pry` anywhere in this script for easy debugging
  31. require 'pry'
  32.  
  33. # Connect to an in-memory sqlite3 database
  34. ActiveRecord::Base.establish_connection(
  35. adapter: 'sqlite3',
  36. database: ':memory:'
  37. )
  38.  
  39. # Define a minimal database schema
  40. ActiveRecord::Schema.define do
  41. create_table :shows, force: true do |t|
  42. t.string :name
  43. end
  44.  
  45. create_table :episodes, force: true do |t|
  46. t.string :name
  47. t.belongs_to :show, index: true
  48. end
  49. end
  50.  
  51. # Define the models
  52. class Show < ActiveRecord::Base
  53. has_many :episodes, inverse_of: :show
  54. end
  55.  
  56. class Episode < ActiveRecord::Base
  57. belongs_to :show, inverse_of: :episodes, required: true
  58. end
  59.  
  60. # Create a few records...
  61. show = Show.create!(name: 'Big Bang Theory')
  62.  
  63. first_episode = show.episodes.create!(name: 'Pilot')
  64. second_episode = show.episodes.create!(name: 'The Big Bran Hypothesis')
  65.  
  66. episode_names = show.episodes.pluck(:name)
  67.  
  68. puts "#{show.name} has #{show.episodes.size} episodes named #{episode_names.join(', ')}."
  69. # => Big Bang Theory has 2 episodes named Pilot, The Big Bran Hypothesis.
  70.  
  71. # Use `binding.pry` here to experiment with this setup.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement