2017-11-16 6 views
0

私は古いPHPアプリケーションを書き直しており、データベースを移行する必要があります。 それは参加 テーブルharddisks_imagecapturingがあります"ヘルパー"テーブルに関するレール協会

id manuscripts_id harddisk_id 
------------------------------- 
1 206    18 
2 206    17 
3 206    16 

表のimagecapturing:

id harddisk_id library signature 
------------------------------- 
1 16   "foo" "MS352" 
2 17   "bar" "AB67" 
3 18   "baz" "WQ62" 

テーブルのハードディスク:

id harddisk_name capacity 
------------------------------- 
16 "Seagate" 2000 
17 "Seagate" 2000 
18 "Seagate" 4000 

問題は、私はmanuscript_idを持っていないということであり、独自の署名であり、原稿テーブルから参照するための「ヘルパーテーブル」として使用することができます。

表の原稿:

id signature 
--------------- 
206 "MS352" 

がどのように私は右の列を持つテーブルにデータを取得するために、Railsの関連付けを行うことができます:

署名、ライブラリー、harddisk_name、容量

?私は、原稿テーブルから署名を得るためにharddisks_imagecapturingテーブルからmanuscript_idを使用しなければならないと思います。

class Imagecapturing < ApplicationRecord 
    self.table_name = 'imagecapturing' 

    belongs_to :harddisk 

end 

class HarddisksImagecapturing < ApplicationRecord 
    self.table_name = 'harddisks_imagecapturing' 

    belongs_to :harddisk 
    belongs_to :imagecapturing 
end 

class Harddisk < ApplicationRecord 
    has_many :manuscripts_harddisks 
    has_many :manuscripts, through: :manuscripts_harddisks 

    default_scope { order(kaufdatum: :desc) } 

    # Harddisk.order('id ASC').reorder('kaufdatum DESC') 
end 

class Manuscript < ApplicationRecord 

end 

答えて

1

あなたは団体のためのprimary_keyforeign_keyとして使用する列(複数可)を指定することができます。あなたが言及したようhttp://guides.rubyonrails.org/association_basics.html#options-for-belongs-to

class Manuscript < ApplicationRecord 
    belongs_to :imagecapturing, foreign_key: "signature", primary_key: "signature" 
end 

あるいは、あなたにもあなたのharddisks_imagecapturingテーブルをナビゲートすることができます。