has_many通过和has_many

时间:2014-03-18 14:35:11

标签: ruby-on-rails ruby ruby-on-rails-3 rspec

我是铁轨开发的新手,所以期待最糟糕的事情。到目前为止,我已经阅读了很多关于此的内容,但我仍然无法找出我做错了什么。

我很难找到创建模型和迁移的正确方法,从而实现下面模型中描述的关系。

This is what I am trying to accomplish

现在这是我的迁移:

    class CreateCoaches < ActiveRecord::Migration
  def change
    create_table :coaches do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.timestamps
    end

    create_table :pupils do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.belongs_to :coach
      t.timestamps
    end

        create_table :talks do |t|
      t.belongs_to :coach

      t.belongs_to :pupil
      t.datetime :talk_date
      t.timestamps
    end
  end
end

这是模特:

class Coach < ActiveRecord::Base
  has_many :talks
  has_many :pupils, through: :talks
  has_many :pupils
end

class Patient < ActiveRecord::Base
  has_many :talks
  belongs_to :coach
  has_many :coaches, through: :appointments

end

class Talk < ActiveRecord::Base
  belongs_to :pupil
  belongs_to :coach
end

这是我试图执行的rspec测试(我希望它不会让你的眼睛流血......)

require 'spec_helper'

describe Coach do
  before(:each) do
    @coach = Coach.create!(first_name: "Förnamn", last_name: "Efternamn")
  end

  it "creates a Coach" do
    Coach.create!(first_name: "Andy", last_name: "Lindeman")

    expect(Coach.find_by_first_name("Andy").first_name).to eq("Andy")

  end   

  it "creates a Coach and a pupil" do

    @coach.pupils << Pupil.create!(first_name:"Donald", last_name:"Duck")
    expect(@coach.pupils[0].first_name).to eq "Donald"

  end
end

错误:

失败/错误:@ coach.pupils&lt;&lt; Pupil.create!(first_name:&#34; Donald&#34;,last_name:&#34; Duck&#34;)      LoadError:        无法自动加载常量Pupil,预计/home/elgrego/Projects/Coachen/app/models/pupil.rb来定义它

此致 Elgrego

2 个答案:

答案 0 :(得分:0)

我认为你拼错了你的模特。你称之为患者,但我认为你的意思是Pupil。此外,最好在迁移中使用t.references而不是belongs_to。但看起来你到目前为止表现还不错。你可能会犯其他一些错误,但我会修复它,看看还有什么不对。

答案 1 :(得分:0)

只是添加到freddyrangel的答案。

修改模型如下:

class Coach < ActiveRecord::Base
  has_many :pupils
  has_many :talks, through: :pupils
end

class Pupil < ActiveRecord::Base
  has_many :talks
  belongs_to :coach    
end

我建议你阅读 Active Record Associations