Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. class Db < ActiveRecord::Base
  2.  
  3. self.abstract_class = true
  4.  
  5. attr_accessor :error
  6.  
  7. def initialize(item = nil)
  8. @error = ""
  9. connect
  10. super
  11. end
  12.  
  13. def connect
  14. could_connect = true
  15. @error = ""
  16.  
  17. begin
  18. ActiveRecord::Base.establish_connection(
  19. :adapter => "mysql2",
  20. :host => "localhost",
  21. :username => "root",
  22. :password => "",
  23. :database => "another_database",
  24. :port => 3306,
  25. :encoding => "utf8"
  26. )
  27. rescue ActiveRecord::ConnectionNotEstablished
  28. @error = "Could not connect to database. The connection was not established"
  29. could_connect = false
  30. rescue Mysql2::Error
  31. @error = "Could not connect to database using MySQL2"
  32. could_connect = false
  33. rescue => e
  34. @error = "Could not connect to database. #{e.message}."
  35. could_connect = false
  36. end
  37.  
  38. return could_connect
  39. end
  40.  
  41. end
  42.  
  43. class Gmodel < Db
  44.  
  45. def initialize(new_table_name)
  46. ActiveRecord::Base.set_table_name(new_table_name)
  47. super
  48. end
  49.  
  50. end
  51.  
  52. class MainController < ApplicationController
  53.  
  54. def index
  55. @users = Gmodel.new("users")
  56. end
  57.  
  58. end
  59.  
  60. undefined method `stringify_keys' for "users":String
  61.  
  62. t = 'some_table'
  63. c = Class.new(ActiveRecord::Base) { self.table_name = t }
  64.  
  65. o = c.find(1)
  66. # 'o' is now a wrapper for the row of some_table where 'id = 1'
  67.  
  68. cols = c.columns.map(&:name)
  69. # 'cols' is now an array of some_table's column names
  70.  
  71. t = 'some_table'
  72. d = 'some_other_database'
  73. c = Class.new(ActiveRecord::Base) do
  74. establish_connection(:adapter => 'mysql2', :database => d, ...)
  75. self.table_name = t
  76. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement