Hi,
I'm new in Rails so I hope to had not made mistakes.
I'm using Rails 3 and AR to build my own web app (in Italian)
and I found a little problem when using has_many association and
composed model names.
The example:
in config/initializers/inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'metodo_pagamento', 'metodi_pagamento' end
in app/models/cliente.rb
class Cliente < ActiveRecord::Base
has_many :metodi_pagamento, :dependent => :destroy end
in app/models/metodo_pagamento.rb
class MetodoPagamento < ActiveRecord::Base
belongs_to :cliente end
so when I run console
ruby-1.8.7-p302 > Cliente.new.metodi_pagamento
I get this
NameError: uninitialized constant Cliente::MetodiPagamento
<======== ( plural form instad singular form )
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/base.rb:1199:in `compute_type'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/reflection.rb:162:in `send'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/reflection.rb:162:in `klass'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/reflection.rb:198:in `quoted_table_name'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/associations/has_many_association.rb:102:in `construct_sql'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/associations/association_collection.rb:24:in `initialize'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/associations/has_many_association.rb:11:in `initialize'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/associations.rb:1492:in `new'
from /home/cristiano/.rvm/gems/ruby-1.8.7-p302/gems/activerecord-3.0.3/lib/active_record/associations.rb:1492:in `metodi_pagamento'
from (irb):2
So, AR doesn't translate the has_many association
:metodi_pagamento in the class MetodoPagamento, but it translate it
in MetodiPagamento (which is the plural form of
MetodoPagamento).
I searched in AR sources and I found the function
derive_class_name in
gems/activerecord-3.0.3/lib/active_record/reflection.rb:
def derive_class_name
class_name = name.to_s.camelize class_name = class_name.singularize
if collection? class_name end
This function try to get the singular form of the model from
Calized form, but in inflections aren't we supposed to write plural
and singular form in underscore form?
So I managed to adjast the function like so:
def derive_class_name
class_name = name.to_s class_name = class_name.singularize if
collection? class_name.camelize end
After this it ran smoothly.
Sure, I could use the :class_name option in model, but...
Punch me if I made mistakes, please.
Thank you