Rails 3 – has_and_belongs_to_many
我有2个模特 – 老师和主题 。 想要通过名称Qualification连接表连接它们。
看起来我做错了什么:
class Teacher "Qualification" end class Subject "Qualification" end
我的迁移:
class CreateQualificationJoinTable 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 console并打印时
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 `' from script/rails:6:in `require' from script/rails:6:in `'
怎么了?
首先,在迁移中创建表不会定义您的模型。 您必须在app/models/qualification.rb
创建一个Qualification
模型:
class Qualification < ActiveRecord::Base belongs_to :subjects belongs_to :teachers end
其次,如果您使用的是Rails 3,请抛弃has_and_belongs_to_many
并使用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
如果您不打算直接使用连接表,则应该只使用has_and_belongs_to_many
。 在您的情况下,如果您不打算使用Qualification本身但仅使用Teacher和Subject,并使用Active Record执行脏工作,请使用它。 如果您与连接模型有任何关系,请使用has_many:through。
在这里阅读更多内容: 在has_many:through和has_and_belongs_to_many之间选择
在rails 3中,最好的方法是通过迁移进行中间表认证
属性将类似于此表
subject_id:整数teacher_id:整数
并且也像这样进行资格认证
class Qualification < ActiveRecord::Base has_many :subjects has_many :teachers end
然后定义其他两个模型
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
并仔细阅读此链接
http://blog.hasmanythrough.com/2007/1/15/basic-rails-association-cardinality