在rails中模拟belongs_to_many

发布于 2024-09-01 12:57:28 字数 291 浏览 1 评论 0原文

我遇到的情况是,理论上我需要使用belongs_to_many 关系。我有一个示例模型和一个句子模型。每个示例对象都有一个句子,但这些句子不一定是唯一的。因此,例如,我可以有两个示例模型,每个模型都有一个句子是同一个句子。我不知道如何在 Rails 中执行此操作。我尝试使用 has_and_belongs_to_many,但遇到了问题。看来我只需要belongs_to:该关系的许多部分。理想情况下它看起来像这样,但我知道没有“belongs_to:many”。

例子 has_one : 句子 结束

句 属于多个:示例 结尾

I have a situation where in theory I would need to use a belongs_to_many relationship. I have an Example model and a Sentence model. Each example object has one sentence but these sentences are not necessarily unique. So, for example, I could have two example models that each have one sentence that is the same sentence. I'm not sure how to go about doing this in rails. I tried using has_and_belongs_to_many, but ran into problems. It seems that I only need the belongs_to :many part of that relationship. Ideally it would look something like this, but I know there is no belongs_to :many.

Example
has_one :sentence
end

Sentence
belongs_to_many :examples
end

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

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

发布评论

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

评论(1

〃安静 2024-09-08 12:57:28

我认为您对数据访问的方向感到困惑。您的代码应如下所示:

# app/models/example.rb
class Example
  belongs_to :sentence
end

# app/models/sentence.rb
class Sentence
  has_many :examples
end

I think you are confused by the direction your data is being accessed from. Here how your code should look like:

# app/models/example.rb
class Example
  belongs_to :sentence
end

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