Rails HABTM关系不适用于多态关系

时间:2013-11-15 15:28:46

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord polymorphic-associations has-and-belongs-to-many

我有两个模型:学生和项目。学生HABTM项目和HABTM项目学生。以下是两种模式:

class Student < User
    has_many :relationships, dependent: :destroy
    has_many :employers, through: :relationships
    has_and_belongs_to_many :projects, join_table: :projects_students
end

class Project < ActiveRecord::Base
    has_many :relationships
    belongs_to :employer
    has_and_belongs_to_many :students, join_table: :projects_students
end

如您所见,Student使用User的多态继承(用户表有一个类型列,其中一个值是Student)。这是创建项目的控制器:

def create
    @project = current_user.projects.new(project_params)

    respond_to do |format|
        if @project.save
            format.html { redirect_to @project, notice: 'Project was successfully created.' }
            format.json { render action: 'show', status: :created, location: @project }
        else
            format.html { render action: 'new' }
            format.json { render json: @project.errors, status: :unprocessable_entity }
        end
    end
end

def project_params
    params.require(:project).permit(:title, :category, :location, :budget,
       :description, :projectdoc)
end

项目和学生通过join_table连接:projects_students:

create_table "projects_students", force: true do |t|
  t.integer "student_id"
  t.integer "project_id"
end

add_index "projects_students", ["project_id"], name: "index_projects_students_on_project_id", using: :btree
add_index "projects_students", ["student_id"], name: "index_projects_students_on_student_id", using: :btree

问题是创建项目时,student_id没有传递给projects_students表。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我认为你的意思是说学生使用“单表继承”而不是“多态继承”,其中没有这样的东西。

那就是说,既然HABTM协会是针对用户而不是学生,我会检查控制台,看看是否有效:

Student.first.projects << Project.first

接下来我要做的是在实例化项目时使用“build”而不是“new”:

@project = current_user.projects.build project_params

我认为这只是用于创建新项目,并且将学生添加到项目中的路径不同。

答案 1 :(得分:0)

我认为你在考虑这个错误。通常,_id保留用于相关表的外键。由于没有Student表,因此rails可能无法正确链接您的联接表中的student_id

尝试更改您的联接表:

create_table "projects_users", force: true do |t|
  t.integer "user_id"
  t.integer "project_id"
end

add_index "projects_users", ["project_id"], name: "index_projects_users_on_project_id", using: :btree
add_index "projects_users", ["user_id"], name: "index_projects_users_on_user_id", using: :btree

您的联接表不应关心您的STI设置。您可以在模型中处理它。

然后只需清理关联:

class Student < User
    has_many :relationships, dependent: :destroy
    has_many :employers, through: :relationships
    has_and_belongs_to_many :projects, join_table: :projects_users, foreign_key: :user_id
end

class Project < ActiveRecord::Base
    has_many :relationships
    belongs_to :employer
    has_and_belongs_to_many :students, join_table: :projects_users, class_name: 'Student', association_foreign_key: :user_id
end