我是一个完整的新手在rails的开发,所以期待最坏的。到目前为止,我已经读了很多关于这方面的文章,但我仍然无法找出我做错了什么。
我很难找到正确的方法来创建模型和迁移,从而实现下面模型中描述的关系。

现在,这是我的迁移:
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 << Pupil.create!(first_name:"Donald",last_name:"Duck") LoadError:无法自动设置常量瞳孔,期望<<来定义它
问候Elgrego
发布于 2014-03-18 14:37:41
我想你拼错了你的模型。你说它有耐心,但我想你是指瞳孔。而且,在迁移中最好是用户t.references而不是belongs_to。但现在看来你做得还不错。你可能犯了其他错误,但我会修复它,看看还有什么不对。
发布于 2014-03-18 14:52:48
只是想补充一下费德·兰格尔的答案。
修改您的模型如下:
class Coach < ActiveRecord::Base
has_many :pupils
has_many :talks, through: :pupils
end
class Pupil < ActiveRecord::Base
has_many :talks
belongs_to :coach
end我建议你读一下关于活动记录协会的书
https://stackoverflow.com/questions/22482505
复制相似问题