ActiveRecord の機能の一部を再作成するプロジェクトに取り組んでいます。ここが機能していない部分です
module Associations
def belongs_to(name, params)
self.class.send(:define_method, :other_class) do |name, params|
(params[:class_name] || name.camelize).constantize
end
self.class.send(:define_method, :other_table_name) do |other_class|
other_class.table_name
end
.
.
.
o_c = other_class(name, params)
#puts this and other (working) values in a query
query = <<-SQL
...
SQL
#sends it off with db.execute(query)...
私はこのテストファイルに向かって構築しています:
require 'all_files' #holds SQLClass & others
pets_db_file_name = File.expand_path(File.join(File.dirname(__FILE__), "pets.db"))
DBConnection.open(pets_db_file_name)
#class Person
#end
class Pet < SQLClass
set_table_name("pets")
set_attrs(:id, :name, :owner_id)
belongs_to :person, :class_name => "Person", :primary_key => :id, :foreign_key => :owner_id
end
class Person < SQLClass
set_table_name("people")
set_attrs(:id, :name)
has_many :pets, :foreign_key => :owner_id
end
.
.
.
私が受け取った何の変化もなく
.../active_support/inflector/methods.rb:230:in `block in constantize': uninitialized constant Person (NameError)
ファイルにクラスをロードする順序に問題があることを確認するために、空の Person クラスでファイルを開始しました。
undefined method `table_name' for Person:Class (NoMethodError)
これは学習プロジェクトであるため、コードを機能させるためにテストを変更したくありません (すべてのクラスを開き、すべてのテーブル/属性を設定してbelongs_to
から、. )
SQLクラスを編集:
class SQLClass < AssignmentClass
extend SearchMod
extend Associations
def self.set_table_name(table_name)
@table_name = table_name
end
def self.table_name
@table_name
end
#some more methods for finding rows, and creating new rows in existing tables
また、AssignmentClass の関連部分はsend
onを使用しattr_accessor
て機能を提供し、クラスの新しいインスタンスをset_attrs
作成する前に、すべての名前が を使用して設定されたものと一致することを確認します。initialize
set_attrs