【问题标题】:Rails : belongs_to and has_many using non-standard idsRails:belongs_to 和 has_many 使用非标准 id
【发布时间】:2011-03-16 08:54:38
【问题描述】:

我有两个模型,Item 和 Product,如下:

irb(main):007:0> Item
=> Item(id: integer, identification_number: string, production_date: date, 
        created_at: datetime, updated_at: datetime, going_in: boolean)
irb(main):008:0> Product
=> Product(id: integer, sku: string, barcode_identification: string, 
           created_at: datetime, updated_at: datetime)

将此视为一个项目属于特定产品。

我已经设法通过

引用特定产品 (Product.find(1).items) 的所有项目
class Product < ActiveRecord::Base
  has_many :items, :foreign_key => "identification_number", 
                   :primary_key => "barcode_identification"
end

但我似乎无法引用特定项目的产品。 这就是我现在得到的:

class Item < ActiveRecord::Base
  set_primary_key :identification_number
  belongs_to :product, :foreign_key => "barcode_identification"
end

据我了解,关于数据库,应该可以。除了它没有。也许我在这里错过了什么?我对 Rails 很陌生(大约一个月或更短时间。)

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    必须是belongs_to吗?既然你指定了主键和外键,为什么不呢

    class Product < ActiveRecord::Base
      has_many :items, :foreign_key => "identification_number", 
                       :primary_key => "barcode_identification"
    end
    
    class Item < ActiveRecord::Base
      has_one :product, :foreign_key => "barcode_identification", 
                        :primary_key => "identification_number"
    end
    

    【讨论】:

    • 您能否详细说明为什么 has_one 有效而 belongs_to 不适用于这种情况?我希望belongs_to 能够工作,但事实并非如此。
    • 有趣。为我工作。谢谢。仍然想知道为什么 belongs_to 不起作用
    • @RonyVarghese belongs_to 如果您正确指定外键和主键,则应该在 Item 中工作:` belongs_to :product, :foreign_key => "identification_number", :primary_key => "barcode_identification"`(注意键与has_many 中的键相同!)查看文档以了解这两种方法的细微差别:apidock.com/rails/ActiveRecord/Associations/ClassMethods/…apidock.com/rails/ActiveRecord/Associations/ClassMethods/…
    【解决方案2】:

    您的 items 表中必须有一个外键。 我假设barcode_identification_id 是项目表中的一列(外键)。 如果您还有其他列,则只需将其替换为该列即可。

    试试这样:

    class Product < ActiveRecord::Base
      set_primary_key :barcode_identification
      has_many :items, :foreign_key => "barcode_identification_id"
    end
    
    class Item < ActiveRecord::Base
      set_primary_key :identification_number
      belongs_to :product
    end
    

    【讨论】:

      猜你喜欢
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多