型号->有_许多->两次

发布于 2024-11-09 03:48:12 字数 676 浏览 0 评论 0原文

因此,注释、组和用户之间的关系有些令人困惑。最后我在模型中出现了两次 has_many 。但我目前专注于 Note & 笔记。团体关系。

背景:一个组可以有一个注释。用户还可以有一个注释。这就是为什么我的 Note 是多态的。不过,我还创建了一个名为 Tag 的连接模型,以便一个 Note 可以属于多个组。但在我的代码中,我最终得到了多个“has_many:notes”。请参阅下面我的所有代码。做这样的事情的正确方法是什么?

提前致谢!

note.rb

belongs_to :notable, :polymorphic => true
has_many :tags
has_many :groups, :through => :tags

用户.rb

has_many :notes, :as => :notable

组.rb

has_many :notes, :as => :notable
has_many :tags
has_many :notes, :through => :tags

标签.rb

belongs_to :note
belongs_to :group

So I have a somewhat confusing relationship here, between a Note, Group, and User. And I ended up with has_many twice in my model. But I'm currently focused on the Note & Group relationship.

Background: A Group can have a note. A User can also have a note. Which is why my Note is polymorphic. However, I also created a join model called a Tag, so that a Note can belong to multiple groups. In my code though, I ended up with multiple 'has_many :notes'. See all of my code below. What would be the proper way to do something like this?

Thanks in advance!

note.rb

belongs_to :notable, :polymorphic => true
has_many :tags
has_many :groups, :through => :tags

user.rb

has_many :notes, :as => :notable

group.rb

has_many :notes, :as => :notable
has_many :tags
has_many :notes, :through => :tags

tag.rb

belongs_to :note
belongs_to :group

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

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

发布评论

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

评论(1

柠檬色的秋千 2024-11-16 03:48:12

您只需给它一个不同的名称。

class Group
  has_many :notes, :as => :notable
  has_many :tags
  has_many :tagged_notes, :class_name => 'Note', :through => :tags
end

如果您只想为添加一个注释:as => :notable 部分(这在你的问题中不是很清楚),你可以这样做:

class Group
  has_one :note, :as => :notable
  has_many :tags
  has_many :notes, :through => :tags
end

名称必须不同。尽管使用 notenotes ,但可能不太清楚代码其他部分的区别。

You just need to give it a different name.

class Group
  has_many :notes, :as => :notable
  has_many :tags
  has_many :tagged_notes, :class_name => 'Note', :through => :tags
end

If you only want a single note for the :as => :notable part (this wasn't very clear in your question), you could just do this:

class Group
  has_one :note, :as => :notable
  has_many :tags
  has_many :notes, :through => :tags
end

The names just have to be different. Although with note vs. notes it might not be very clear what the distinction is in other parts of your code.

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