【问题标题】:foreign key in ruby on rails applicationruby on rails 应用程序中的外键
【发布时间】:2012-12-26 12:47:43
【问题描述】:

我在 Ruby on Rails 应用程序中有三个模型:

  1. 杂志
  2. 产品
  3. 页面

我想使用这个查询:

Magazine.find(1).products.first.pages

并获取与相应产品相关联的页面 但在页面模型中,我不希望 product_id 成为我的外键,我希望 number_id 成为我的外键。 number 是产品表中的一个字段。 如何更改外键?因为 rails 使用 product_id 作为页表的外键。 tnx 为您提供帮助。

【问题讨论】:

    标签: ruby-on-rails ruby database sqlite


    【解决方案1】:

    我将为您的模型编写适当的代码。

    class Magazine < ActiveRecord::Base
      has_many :products
      has_many :pages, :through => :products
    end
    
    
    class Product < ActiveRecord::Base
      set_primary_key "number"
      belongs_to :magazine
      has_many :pages, foreign_key: "product_number"
    
      def my_pages
        self.pages.find_all { |p| p.magazine_id == self.magazine_id}
      end  
    end
    
    class Page < ActiveRecord::Base
    end
    

    您可以致电 Magazine.first.products.first.my_pages

    它会返回正确的结果。

    【讨论】:

      【解决方案2】:

      API 文档提供了所有答案。请参阅options for #has_many。您可能希望以这种方式指定关系:

      class Page < ActiveRecord::Base
        belongs_to :product, foreign_key: "number_id"
      end
      
      class Product < ActiveRecord::Base
        has_many :pages
      end
      

      您的问题对我来说并不完全清楚,但如果您的产品表的主键不是 :id 那么您还需要指定 primary_key: "number" 或您的主键是什么。

      【讨论】:

      • 如果你测试这个查询 Magazine.first.products.first.pages ,你会得到所有与 number_id 相关联的页面并忽略 magazine_id !!!我想考虑他们两个。例如,我希望上面的查询给我与杂志 A 中的产品 B 相关的确切页面。
      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-14
        • 1970-01-01
        • 2023-04-01
        • 2011-05-15
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多