【问题标题】:Unexpected behaviour in rails when defining class_name in habtm在 habtm 中定义 class_name 时,rails 中的意外行为
【发布时间】:2014-04-24 05:21:52
【问题描述】:

我有两个模型(Course 和 Dancer)。一个课程可以有很多舞者(学生)和老师(也是舞者)。教师可以是其他课程的学生。

我将表格定义如下:

create_table "course_enrollments", :force => true do |t|
    t.integer    "dancer_id",     :null => false
    t.integer    "course_id",     :null => false
    t.datetime "attended_on", :null => false
end

create_table "courses", :force => true do |t|
    t.string     "name",             :null => false
    t.string     "genre"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
end

create_table "courses_teachers", :id => false, :force => true do |t|
    t.integer "course_id",    :null => false
    t.integer "teacher_id", :null => false
end

create_table "dancers", :force => true do |t|
    t.string     "first_name", :null => false
    t.string     "last_name",    :null => false
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
end

还有课程:

class Dancer < ActiveRecord::Base
    has_many :course_enrollments
    has_many :courses, :through => :course_enrollments
    has_many :teachers, :through => :courses
end

class Course < ActiveRecord::Base
    has_many :course_enrollments
    has_many :dancers, :through => :course_enrollments
    has_and_belongs_to_many :teachers, :class_name => 'Dancer'
end

class CourseEnrollment < ActiveRecord::Base
    belongs_to :dancer
    belongs_to :course
end

根据指南 (http://guides.rubyonrails.org/association_basics.html),我希望 Course 的教师属性查找表 courses_teachers 并使用teacher_id 作为外键。相反,它正在寻找 course_dancers 和 dancer_id,大概是从将 class_name 设置为“Dancer”。这是设计使然还是错误?如果我这样做,我可以让它工作:

has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers

并在 course_teachers 表中将 teacher_id 重命名为 dancer_id

有更好的方法吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    如果您查看api for habtm,则可以选择foreign_keyassociation_foreign_key。试试下面的

    has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers, :foreign_key => :course_id, :association_foreign_key => :teacher_id
    

    我不确定如果不通过 foreign_key 选项它是否可以工作,但它可能会先尝试不使用它。

    【讨论】:

    • 有效(有/没有foreign_key集)。我是否独自认为“has_and_belongs_to_many :teachers”应该查看 course_teachers 并使用 teacher_id 而不管是否指定了 class_name ?对于如此微不足道/直截了当的内容,似乎需要输入很多内容。
    • 在我看来,一旦设置了class_name,推导join_tableforeign_key 值的过程就会变得模棱两可。我确实认为这里看到的当前行为是理智的,如果这值得的话。
    猜你喜欢
    • 2013-03-23
    • 2019-08-08
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多