Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding model name of a has_many relationship

It would be nice if there was a more elegant way of doing 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 redundant to have to include forum_ in front of sub_topics because I know I'm dealing with a forum_topic. I could change the name of the table/model to SubTopic but that is a bit generic and could possibly come up somewhere in the application. Is there a way to override the name of the methods created on ForumTopic for the has_many association?

Models:

class ForumTopic...
  has_many :forum_sub_topics
end

class ForumSubTopic...
end

Ah the answer is right here. Thanks! :) http://guides.rubyonrails.org/association_basics.html

like image 693
recursive_acronym Avatar asked Dec 27 '22 21:12

recursive_acronym


2 Answers

Try this:

has_many :sub_topics, :class_name => "ForumSubTopic"

Reference

ActiveRecord::Associations::ClassMethods has_many - see under Options

like image 63
mbreining Avatar answered Jan 12 '23 23:01

mbreining


Yes, you can specify whatever association name you want and still tell it to use your ForumSubTopic class:

class ForumTopic
  has_many :sub_topics, :class_name => "ForumSubTopic", :foreign_key => "forum_sub_topic_id"
end
like image 28
Dylan Markow Avatar answered Jan 13 '23 00:01

Dylan Markow