2017-04-21 39 views
0

條件:如何與兩個數據模型構建M至m關係

導師可以按照或DIS遵循學生

學生可以按照或DIS跟隨導師

,教師和學生是兩個不同的數據模型。

我建立名爲application中間數據模型連接兩個模型

應用模型:

class CreateApplications < ActiveRecord::Migration 
    def change 
    create_table :applications do |t| 

     t.belongs_to :tutor, index: true 
     t.belongs_to :student, index: true 

     t.timestamps null: false 
    end 
    end 
end 

application.rb中

class Application < ActiveRecord::Base 
    belongs_to :tutor 
    belongs_to :student 
end 

student.rb

has_many :applications, :dependent => :destroy 
    has_many :tutors, through: :applications 

tutor.rb

has_many :applications, :dependent => :destroy 
    has_many :students, through: :applications 

schema.rb

ActiveRecord::Schema.define(version: 20170421093747) do 

    create_table "applications", force: :cascade do |t| 
    t.integer "tutor_id" 
    t.integer "student_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    add_index "applications", ["student_id"], name: "index_applications_on_student_id" 
    add_index "applications", ["tutor_id"], name: "index_applications_on_tutor_id"....... 

show.html.erb

# -->show who is the follower & person who followed & How many of them 
# Error :undefined method `student' for nil:NilClass 


    <%= @application.student.count %> #undefined method `student' for nil:NilClass 
    <%= @application.tutor.count % >#undefined method `student' for nil:NilClass 

    <%= @application.student%> #undefined method `student' for nil:NilClass 
+0

您的@application變量爲零。你可以在相關的控制器代碼的位置發佈信息嗎? – mysmallidea

+0

@mysmallidea class ApplicationController evalwt

+0

請編輯您的問題,並添加代碼存在而不是顯示在評論它。 – Gerry

回答

0

當模型與其他模型要使用複數名稱一對多的關係,即導師.students或student.tutors

UPD:另外,您沒有將變量正確傳遞到視圖中,請檢查您的cont滾筒。如果你想將它重命名爲類似課程,類或StudentTutor之類的東西,因爲Application.rb是默認情況下所有模型都繼承的模型,同樣的, ApplicationController的)。它總是有一名學生和一名導師(它屬於兩種模式)。如果你想計算你想找的學生的相關記錄(如果你想數他的導師)或導師(反之亦然)

+0

你的意思是應用程序屬性? – evalwt

+0

我的意思是作爲返回相關活動記錄數組的模型公共方法。這就是Rails約定如何指定has_many和belongs_to關係。因爲你已經指定了has_many,所以你不需要明確地對應用程序做任何事情。 –

1

在你的控制器中,你需要設置@application變量。

def show 
    @application = Application.find(params[:id]) 
end 

我強烈建議不要命名這個類Application。 「應用程序」這個詞在Rails中有特殊含義,你幾乎肯定會遇到衝突。 ApplicationController也是如此。

+0

然後,我應該把上面的代碼放在最初的'ApplicationController'或一個新的'ApplicationController'上? – evalwt

+1

您應該重新開始一個新的控制器和模型,銷燬您剛剛創建的名爲「Application」的控制器和模型。 Ruby有很多保留字。通過避免使用它們作爲名字,你將爲自己節省很多頭痛。 https://reservedwords.herokuapp.com/。 –