2016-09-16 126 views
0

我在一週前創建了我的模型,但我不知道很多我現在知道的事情,所以現在是時候從頭開始創建它。Rails多對多協會和has_many,通過:

我要實現什麼目標是創建:

,可以有很多的優惠
  • 發售模式,可以有許多實驗室

    1. 實驗室模型。

      #MIGRATION FILES BELOW: 
      class CreateLabs < ActiveRecord::Migration[5.0] 
          def change 
          create_table :labs do |t| 
           t.string :name 
           ... 
      
           t.timestamps 
          end 
          end 
      end 
      
      class CreateOffers < ActiveRecord::Migration[5.0] 
          def change 
          create_table :offers do |t| 
           t.string :name 
           ... 
      
           t.timestamps 
          end 
          end 
      end 
      
      # Join table: 
      class CreateLabChain < ActiveRecord::Migration[5.0] 
          def change 
          create_table :lab_chain do |t| 
           t.references :lab, foreign_key: true 
           t.references :offer, foreign_key: true 
           t.timestamps 
          end 
          end 
      end 
      

    這裏是模型文件什麼樣子:

    class Lab < ApplicationRecord 
        has_many :offers, through: :lab_chain 
        has_many :lab_chains 
    end 
    
    class Offer < ApplicationRecord 
        has_many :labs, through: :lab_chain 
        has_many :lab_chains 
    end 
    
    class LabChain < ApplicationRecord 
        belongs_to :lab 
        belongs_to :offer 
    end 
    

    我只是想知道,如果我正確地寫了這一切,因爲我不知道所有這些我都看過教程並閱讀。

    獎勵的問題是,如果我想要我的優惠有很多部分,節有很多offer_items?我是不是應該加上:

    提供的:

    has_many :sections 
    has_many :offer_items, through: :section 
    

    再到科:

    has_many :offer_items 
    belongs_to :offer 
    

    和以OfferItem:

    belongs_to :section 
    

    ? 正如我之前提到的,我自願作爲一個爲我們學校項目製作網站的人,因爲我是唯一一個與代碼(不同語言)有關的人。這比我想象的要難。

    編輯

    我怎麼會還正確地添加自第加盟,讓一個部分可以有一個小節等等?

    自聯接addded到添加到遷移文件

    t.references :parent_section, foreign_key: "section_id" 
    
  • 回答

    1

    科模型

    has_many :child_sections, class_name: "Section", foreign_key: "section_id" 
    belongs_to :parent_section, class_name: "Section" 
    

    這看起來像一個正確的多對多關聯。你秒也看起來正確。另外,它有助於繪製任何超過3個表的數據庫的圖表,如果您計劃將其作爲一項工作來完成,那麼完全掌握整個表關係非常值得,因爲它是寫作的核心好的模型代碼。

    +0

    感謝您的建議!如果我想將自連接添加到節模型會怎麼樣?那麼一個部分可以有子部分?編輯代碼包括 – Ancinek

    +1

    @Ancinek你不需要一個子部分模型/表,特別是如果你想做自我加入。你的分區表應該有一個parent_id列。當一個類別的parent_id值指向另一個類別記錄時,該類別就是一個子類別。帶有空parent_id的類別是頂級類別。所以你可以有一個代碼,比如has_many:sub_section,class_name:「Section」,foreign_key::parent_id,那麼你應該創建一個遷移來將parent_id列添加到sections表中。 –