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
Try this:
has_many :sub_topics, :class_name => "ForumSubTopic"
ActiveRecord::Associations::ClassMethods has_many - see under Options
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With