覆盖 has_many 关系的模型名称

发布于 2024-11-06 02:52:47 字数 683 浏览 0 评论 0 原文

考虑到这些模型,如果有一种更优雅的方法来做到这一点,那就太好了:

@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

必须在 sub_topics 前面包含 forum_ 似乎是多余的,因为我知道我正在处理 forum_topic。我可以将表/模型的名称更改为 SubTopic,但这有点通用,可能会出现在应用程序中的某个位置。 是否有办法覆盖在 ForumTopic 上为 has_many 关联创建的方法的名称?

模型:

class ForumTopic...
  has_many :forum_sub_topics
end

class ForumSubTopic...
end

啊,答案就在这里。谢谢! :) http://guides.rubyonrails.org/association_basics.html

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫罗兰の梦幻 2024-11-13 02:52:47

试试这个:

has_many :sub_topics, :class_name => "ForumSubTopic"

参考

ActiveRecord::Associations::ClassMethods has_many - 请参阅选项

Try this:

has_many :sub_topics, :class_name => "ForumSubTopic"

Reference

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

假情假意假温柔 2024-11-13 02:52:47

是的,您可以指定您想要的任何关联名称,并仍然告诉它使用您的 ForumSubTopic 类:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文