Rails:使用非标准ID的belongs_to和has_many

Rys*_*aum 9 activerecord ruby-on-rails

我有两个型号,项目和产品如下:

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)
Run Code Online (Sandbox Code Playgroud)

您可以将其视为特定产品.

我已经设法通过引用特定产品(Product.find(1).items)的所有项目

class Product < ActiveRecord::Base
  has_many :items, :foreign_key => "identification_number", 
                   :primary_key => "barcode_identification"
end
Run Code Online (Sandbox Code Playgroud)

但我似乎无法推荐特定产品的产品.这就是我现在所拥有的:

class Item < ActiveRecord::Base
  set_primary_key :identification_number
  belongs_to :product, :foreign_key => "barcode_identification"
end
Run Code Online (Sandbox Code Playgroud)

就我的理解而言:数据库,这应该工作.除了它没有.也许我错过了这里的一些东西?我对rails很新(大约一个月或更短的时间.)

Sim*_*mon 16

它必须是一个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
Run Code Online (Sandbox Code Playgroud)

  • 您能否详细说明在这种情况下has_one为何起作用而belongs_to不起作用?我希望belongs_to工作,但事实并非如此。 (2认同)