【问题标题】:HABTM not working with polymorphic association in railsHABTM 不适用于 Rails 中的多态关联
【发布时间】:2013-11-28 04:06:02
【问题描述】:

我有一个多态关联:我的用户模型可以是“学生”类型或“雇主”类型。我正在尝试在学生模型和另一个称为“项目”模型的模型之间建立 has_and_belongs_to_many 关联。当我尝试打电话时:

控制器:

@my_projects = current_user.projects 

查看:

<% @my_projects.where(state: :posting).each do |project| %>
    <%= project.students %><br>
<% end %> 

有人告诉我:

PG::UndefinedTable: ERROR:  relation "projects_users" does not exist

我已经定义了一个名为“projects_students”的表,我认为它应该可以工作。我不想有一个“project_users”表,因为该表仅适用于学生,不适用于雇主。我该如何解决?这是我的模型:

class Student < User
    has_and_belongs_to_many :projects
end

-

class Project < ActiveRecord::Base
    has_and_belongs_to_many :students
end

【问题讨论】:

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


    【解决方案1】:

    您正在从 User 对象的起始上下文构建 @my_projects。如果你从 Rails 控制台运行User.first.projectsStudent.first.projects,你会看到一个尝试使用projects_users 作为连接表,而另一个尝试使用projects_students。因此,不要像我最初建议的那样在模型中强制使用特殊的“join_table”名称,您可以在查找项目时执行以下操作:

    @my_projects = current_user.becomes(Student).projects
    

    【讨论】:

    • 谢谢,它有效。但这是一个不好的做法吗?它不应该自动知道连接表吗?此外,由于某种原因,在创建连接表时,student_id 没有被传递给它。
    • 好的,现在我看到了真正的问题。我已经更新了我的答案以提供另一个避免在模型中明确定义 join_table 名称的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    相关资源
    最近更新 更多