【问题标题】:Rails N-Table RelationshipsRails N 表关系
【发布时间】:2014-04-10 15:17:02
【问题描述】:

我很难理解 Rails 的自动魔力。现在我有 4 个不同的表,它们都以一种或另一种方式相互关联,但我很难在我的应用程序中表示它。我能够在 PHP/MySQL 中毫无问题地做到这一点,但将其转换为新框架并不像我预期的那么容易。

现在我有 4 张桌子,但我以后还会有更多模仿这种相同结构的桌子。当前的四个表是(rails 类表示):

  • 用户
  • 兴趣页面
  • 兴趣页面类别
  • 兴趣页面地图

每个用户通过 InterestPageMap 有_many InterestPage(s)

每个 InterestPage 都属于_to InterestPageCategory,而这又具有_many InterestPage(s)

当我为给定用户添加新的 InterestPage 时,我首先需要确保 InterestPageCategory 存在并且 InterestPage 链接回正确的类别。处理这种关系的最佳方式是什么?

我现在使用的方法给了我这个错误:

uninitialized constant User::InterestPageCategory

所以我认为我离我想要做的事情还很远。我的用户类代码如下所示:

has_many :interest_page_maps, foreign_key: "fb_id", dependent: :destroy
...
category = InterestPageCategory.where(category: resp["category"]).first_or_create
# Then I try to add the page with the correct category
page = InterestPage.where(resp[0]).first_or_create do |interestpage|
    # Should I be adding the page through the category in this block?
    interestpage.name = resp["name"]
    interestpage.id = resp["id"]
end

任何提示或建议将不胜感激。谢谢!

【问题讨论】:

  • category = 和 page = 是一个方法的一部分吗?
  • User 模型下的方法相同。基本上,该方法调用 Facebook Graph API 并返回一组用户喜欢的页面。
  • 你有没有像self.interest_pages << page这样的方法
  • 方法中没有类似的东西。我创建了一个新项目只是为了测试我想要建立的关系的基本结构并且测试项目有效,这意味着我在这个项目中有错字或某些导致问题的东西。当我有时间跟踪它时,我会在这里发布,今天还有一些其他的客户工作要完成。

标签: ruby-on-rails database activerecord ruby-on-rails-4


【解决方案1】:

结果证明这是我的一个错字。 Rails 在生成关系时引用文件名而不是类名,即:

包含 InterestPageCategory 类的文件被命名为interest_page_categories.rb。这是不正确的,该文件需要具有名称 interest_page_category.rb(单数与复数)才能让 Rails “看到”我试图引用的类。

希望这对其他人有所帮助,不要忘记检查您的命名人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多