This project is archived and is in readonly mode.
class method to_s used instead of name
Reported by Hery | May 30th, 2009 @ 03:33 PM | in 2.x
Hi,
Here is an issue/improvement/suggestion
When defining a to_s class method for my models it breaks rails,
especially in active_record.
active_record uses both class.name and class.to_s to do the same
sort of stuffs (like in the join_table_name in associations)
I think class.name is the name of the class and to_s is a string
representation. But by default class.name == class.to_s
I think self.to_s should not be used for building such things like
table names, instead use name.
The problem occurs when I want to distinguish my simple class
and my active_record models (I also use to_s for other cases)
It is a basic code ....
I just create user and project activerecord classes with a habtm associations.
I put at the bottom of config/environment.rb
module ActiveRecord
class Base
def self.to_s
"ActiveRecord::Base model : #{self.name}"
end
end
end
Since I implement this simple code I run into troubles!
I launch script/console to see what is the problem and I see that my User.reflections[:projects].options[:join_table] is not what is expected
User.reflections[:projects].options[:join_table] => "base model : users_projects" It should return "users_projects" !!!!
E.g in version 2.3.2 in activerecord/lib/active_record/associations.rb:1538 If find the code which gives me headhache.
reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
The guilty code is ( mine ? :) ) described above. I replace
undecorated_table_name(self.to_s) by
undecorated_table_name(self.name) and other things like that, runs
all the tests well
But I think i missed some.
I know that many libraries use to_s and name for the same things. My question is : "Is it clean?"
I think there are many bugs like this .... And why not only use name, since name and to_s class methods return by default the same results ?
Hery
Comments and changes to this ticket
-
David Trasbo April 15th, 2010 @ 10:06 PM
- Assigned user set to Ryan Bigg
Basically, overriding pretty much any method in
ActiveRecord::Base
breaks Rails. You have to be very careful with that. If you think this should be fixed, please provide a patch. Meanwhile, this can be marked as invalid. -
Ryan Bigg April 15th, 2010 @ 10:35 PM
- State changed from new to wontfix
Solution: don't define to_s for the model. It needs this to figure out table names iirc.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>