尝试删除 Rails 中的 has_and_belongs_to_many 关系

发布于 2024-07-13 10:07:50 字数 885 浏览 8 评论 0原文

所以我昨天才开始我的第一个 Rails 项目。 我的应用程序中有两个多对多(has_and_belongs_to_many)关系。 我在模型比赛和球队之间建立了一个模型,在模型统计数据和结果之间建立了另一个模型。 通过自己通过迁移创建连接表,这一切都工作得很好。

然后我决定我不想让统计/结果关系成为多对多,而是多对多,所以我运行了以下迁移并将关系切换为 has_many 和属于_to:

class FixingResultStatRelationship < ActiveRecord::Migration
  def self.up
    add_column :results, :stat_id, :integer
    drop_table "results_stats"
  end

  def self.down
   remove_column :results, :stat_id
   create_table "results_stats", :id => false do |t|
      t.column "result_id", :integer
      t.column "stat_id", :integer
    end
    add_index "results_stats", "result_id"
    add_index "results_stats", "stat_id"
  end
end

然后,当我这样做时,它不仅新的一对多关系不起作用,因为我在调用 Result.find(0).stat 时收到 NoMethodError 错误,但现在我之前与游戏和团队的工作多对多关系现在也被打破了。 我曾经能够调用 Game.fine(0).teams 只是查找并查看结果,现在我也得到了 NoMethodError 。 有什么想法吗? 我很迷失,任何帮助都会很棒。

So I just started my first rails project yesterday. I had two many-to-many (has_and_belongs_to_many) relationships in my application. I had one between models games and teams and another between models stats and results. This was all working just fine by creating the join table myself with a migration.

I then decided that I did not want to have the stats/results relationship be many-to-many but what to many instead so I ran the following migration and switched the relationships to has_many and belongs_to:

class FixingResultStatRelationship < ActiveRecord::Migration
  def self.up
    add_column :results, :stat_id, :integer
    drop_table "results_stats"
  end

  def self.down
   remove_column :results, :stat_id
   create_table "results_stats", :id => false do |t|
      t.column "result_id", :integer
      t.column "stat_id", :integer
    end
    add_index "results_stats", "result_id"
    add_index "results_stats", "stat_id"
  end
end

Then when I do this it not only does the new one-to-many relationship not work as I get a NoMethodError when calling say Result.find(0).stat but now my previous working many-to-many relationship with games and teams is now broken as well. I used to be able to call Game.fine(0).teams just find and see the results and now I get a NoMethodError as well. Any thoughts? I am quite lost and any help would be great.

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

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

发布评论

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

评论(1

请远离我 2024-07-20 10:07:50

我刚刚意识到我有 own_to :stats 而不是单一的 stat。 我修复了这个问题并重新加载了服务器,现在一切正常。 不管怎样还是谢谢阿比。

I just realized that I had belongs_to :stats rather than the singular stat. I fixed this and reloaded the server and everything works fine now. Thanks anyways though Abie.

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