Ruby on rails Rails:属于并且有很多使用非标准ID
我有两种型号,项目和产品如下:Ruby on rails Rails:属于并且有很多使用非标准ID,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有两种型号,项目和产品如下: 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:
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 Item < ActiveRecord::Base
set_primary_key :identification_number
belongs_to :product, :foreign_key => "barcode_identification"
end
class项“条形码\标识”
结束
就我对re:数据库的理解而言,这应该是可行的。但事实并非如此。也许我错过了什么?我对rails相当陌生(大约一个月或更少。)您的items表中必须有一个外键。 我假设barcode_identification_id是items表中的一列(外键)。 如果你有其他的专栏,那就用它来代替吧 试着这样做:
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
类产品“条形码\u标识\u id”
结束
类项
它必须是属于的吗?既然您同时指定主键和外键,为什么不呢
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
类产品“标识号”,
:主键=>“条形码识别”
结束
类项“条形码识别”,
:主键=>“标识号”
结束
您能否详细解释一下为什么在这种情况下“一个”可以工作,而“一个”不能工作?我希望你能去工作,但这并不有趣。为我工作。谢谢还在想为什么你不属于我work@RonyVarghese如果正确指定外键和主键,属于
应该在项中起作用:`behing\u to:product,:foreign\u key=>“identification\u number”,:primary\u key=>“barcode\u identification”`(请注意,中的键与有许多
!)查看文档了解这两种方法的细微区别:和
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