Overriding the has_many relationship model name

It would be nice if there was a more elegant way to do this, given these models:

@forum_topic = ForumTopic.find(1) @forum_topic.forum_sub_topics.each do |fst| #it would be nicer if one could just type @forum_topic.sub_topics.each... # end 

It seems unnecessary to include forum_ in front of sub_topics, because I know that I am dealing with forum_topic. I could change the table / model name to SubTopic, but this is a bit common and might appear somewhere in the application. Is there a way to override the name of methods created in ForumTopic for the has_many association?

Models:

 class ForumTopic... has_many :forum_sub_topics end class ForumSubTopic... end 

And here is the answer right here. Thank you! :) http://guides.rubyonrails.org/association_basics.html

+4
source share
2 answers

Try the following:

 has_many :sub_topics, :class_name => "ForumSubTopic" 
+7
source

Yes, you can specify any association name you want and still use it to use the ForumSubTopic class:

 class ForumTopic has_many :sub_topics, :class_name => "ForumSubTopic", :foreign_key => "forum_sub_topic_id" end 
+3
source

All Articles