Why associations get error when defined in abstract_class model

I have many models and want to share common functions among them in
abstract_class models as many as possible.

But why the associations specified in abstract_class do not work?

For example:

class Property < AR::Base
self.abstract_class = true

belongs_to :dictionary, :foreign_key=>‘dictionary_id’, :class_name
=>"#{self.class.parent.name}::Dictionary"
#############
I did this instead of specify them in Jp::Property and Cn::Property
seperately.
In Jp::Property
belongs_to :dictionary, :foreign_key=>‘dictionary_id’, :class_name
=>“Jp::Dictionary”
In Cn::Property
belongs_to :dictionary, :foreign_key=>‘dictionary_id’, :class_name
=>“Cn::Dictionary”
#############

end

class Dictionary < AR::Base
self.abstract_class = true
end

class Jp::Property < Property
set_table_name :jp_properties
end

class Jp::Dictionary < Dictioanry
set_table_name :jp_dictionaries
end

class Cn::Property < Property
set_table_name :cn_properties
end

class Cn::Dictionary < Dictioanry
set_table_name :cn_dictionaries
end

when I fire up console when input this

temp = Jp::Property.first => first property record
temp.dictionary

NameError: uninitialized constant Dictionary
from /rails/activesupport/lib/active_support/dependencies.rb:443:in
load_missing_constant' from /rails/activesupport/lib/active_support/dependencies.rb:80:inconst_missing’
from /rails/activesupport/lib/active_support/dependencies.rb:92:in
const_missing' from /rails/activerecord/lib/active_record/base.rb:2204:incompute_type’
from /rails/activesupport/lib/active_support/core_ext/kernel/
reporting.rb:11:in silence_warnings' from /rails/activerecord/lib/active_record/base.rb:2200:incompute_type’
from /rails/activerecord/lib/active_record/reflection.rb:156:in
send' from /rails/activerecord/lib/active_record/reflection.rb:156:inklass’
from /rails/activerecord/lib/active_record/associations/
belongs_to_association.rb:44:in find_target' from /rails/activerecord/lib/active_record/associations/ association_proxy.rb:240:inload_target’
from /rails/activerecord/lib/active_record/associations/
association_proxy.rb:112:in reload' from /rails/activerecord/lib/active_record/associations.rb:1230:indictionary’

Can you please explain this?

I think maybe I figured out why I’m wrong.

The ‘belongs_to’ declaration in abstract class is actually evaluated
before the abstract class is inherited.

And the sub class which is inherited from abstract class only got all
the instance methods which were generated by the ‘belongs_to’
declaration in its parent.

So, in my example,

I can never get ‘Jp’ or ‘Cn’ strings in the abstract class Property’s
‘belongs_to’ declaration because the instance object ‘temp’ never saw
that declaration.

Please fix me if I am wrong.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs