Rails 3 - has_and_belongs_to_many [英] Rails 3 - has_and_belongs_to_many
本文介绍了Rails 3 - has_and_belongs_to_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个模型 - Teacher 和 Subject.A 想通过名称为 Qualification 的 Join 表连接他们.
I have 2 models - Teacher and Subject. A want to connect them via Join table with name Qualification.
看来我做错了什么:
class Teacher < ActiveRecord::Base
has_and_belongs_to_many :subjects, :join_table => "Qualification"
end
class Subject < ActiveRecord::Base
has_and_belongs_to_many :teachers, :join_table => "Qualification"
end
我的迁移:
class CreateQualificationJoinTable < ActiveRecord::Migration
def change
create_table :qualification, :id => false do |t|
t.integer :subject_id
t.integer :teacher_id
end
add_index :qualification, :subject_id
add_index :qualification, :teacher_id
end
end
例如,当我打开 rails 控制台并打印时
When i open rails console and print, for example
ruby-1.9.3-head :013 > Qualification
我明白了:
NameError: uninitialized constant Qualification
from (irb):13
from /Users/serg/.rvm/gems/ruby-1.9.3-head/gems/railties-3.2.0/lib/rails/commands/console.rb:47:in `start'
from /Users/serg/.rvm/gems/ruby-1.9.3-head/gems/railties-3.2.0/lib/rails/commands/console.rb:8:in `start'
from /Users/serg/.rvm/gems/ruby-1.9.3-head/gems/railties-3.2.0/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
怎么了?
推荐答案
首先,在迁移中创建表并不会定义您的模型.您必须在 app/models/qualification.rb
中创建一个 Qualification
模型:
First, creating the table in a migration doesn't define your model. You have to create a Qualification
model in app/models/qualification.rb
:
class Qualification < ActiveRecord::Base
belongs_to :subjects
belongs_to :teachers
end
其次,如果您使用的是 Rails 3,请扔掉 has_and_belongs_to_many
并使用 has_many :through
:
Second, if you're using Rails 3, throw out has_and_belongs_to_many
and use has_many :through
:
class Teacher < ActiveRecord::Base
has_many :qualifications
has_many :subjects, :through => :qualifications
end
class Subject < ActiveRecord::Base
has_many :qualifications
has_many :teachers, :through => :qualifications
end
这篇关于Rails 3 - has_and_belongs_to_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文