Forum: Ruby on Rails Possible bug: ActiveRecord::Base::has_many fails for String

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B780ee0ee1480454a85df58536702f63?d=identicon&s=25 Alder Green (Guest)
on 2006-05-16 10:11
(Received via mailing list)
Hi

I've noticed ActiveRecord::Base::has_many fails for String arguments.
The following code works when all arguments to the
ActiveRecord::Base::has_many calls are Symbols:

class Country < ActiveRecord::Base
  has_many :country_products, :dependent => true
  has_many :products, :through => :country_products
end

ruby script/console
>> Country.find_all.first.products
[#<Product:0x313f4d8 @attributes={"name"=>"pencil", "id"=>"1"}>]

But once we change some of them to Strings the same code fails
mysteriously:

class Country < ActiveRecord::Base
  has_many "country_products", :dependent => true
  has_many :products, :through => :country_products
end
>> Country.find_all.first.products
ActiveRecord::HasManyThroughAssociationNotFoundError:
ActiveRecord::HasManyThroughAssociationNotFoundError

class Country < ActiveRecord::Base
  has_many :country_products, :dependent => true
  has_many "products", :through => :country_products
end
>> Country.find_all.first.products
NoMethodError: undefined method `id2name' for "products":String

class Country < ActiveRecord::Base
  has_many :country_products, :dependent => true
  has_many :products, :through => "country_products"
end
>> Country.find_all.first.products
ActiveRecord::HasManyThroughAssociationNotFoundError:
ActiveRecord::HasManyThroughAssociationNotFoundError

This situation is - at best - very confusing. Rails seems to be
completely liberal about getting Strings instead of Symbols in other
places. And even if there would be a decision to make Rails less
promiscuous in this regard - which isn't necessarily a bad thing - it
should do a better job at informing the developer. Especially since
this strictness is inconcistent with the rest of the framework. Notice
how mysterious the error messages we got - and that we got two
completely different errors for what is essentially the same problem.

Anyone has a different take on this?  I'm planning to file this as a
bug.
This topic is locked and can not be replied to.