如何在两个数据模型之间建立M与M关系



条件:

导师可以关注或删除学生

学生可以关注或删除教师

导师和学生是两个不同的数据模型。

i构建了一个称为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

在您的控制器中,您需要设置@Application变量。

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

我强烈建议不要命名此类Application。"应用程序"一词在铁轨中具有特殊的含义,几乎可以肯定会遇到冲突。ApplicationController也是如此。

当模型与其他模型有许多关系时,您想使用复数名称,即导师,学生或学生。Tutors.Tutors

upd:另外,您没有正确地将变量传递到视图中,请检查控制器。

upd1:另外,使用计数在应用程序记录上是毫无意义的(顺便说一句,您想将其重命名为课程,课程或仅仅是学生培训,因为application.rb是默认情况下您的所有模型,默认情况下,同样的是Application Controller(。它总是有一个学生和一位导师(属于这两种模型(。如果您想计算相关记录

最新更新