Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

class method to_s used instead of name

#2742

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

Reported by Hery · May 30th, 2009 @ 03:33 PM

State: wontfix
Milestone: 2.x
Assigned to: Ryan Bigg Ryan Bigg
Importance: none

Activity

  1. David Trasbo
    David Trasbo
    • 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.

    April 15th, 2010 @ 10:06 PM

  2. Ryan Bigg
    Ryan Bigg
    • State changed from new to wontfix

    Solution: don't define to_s for the model. It needs this to figure out table names iirc.

    April 15th, 2010 @ 10:35 PM