简体   繁体   English

HABTM无法与Rails中的多态关联一起使用

[英]HABTM not working with polymorphic association in rails

I have a polymorphic association: my user model can be of type 'student' or of type 'employer'. 我有一个多态关联:我的用户模型可以是“学生”类型或“雇主”类型。 I am trying to set up a has_and_belongs_to_many association between the student model and another model called the 'project' model. 我正在尝试在学生模型和另一个称为“项目”模型的模型之间建立has_and_belongs_to_many关联。 When I try to call: 当我尝试致电时:

controller: 控制器:

@my_projects = current_user.projects 

view: 视图:

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

I am told: 有人告诉我:

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

I have defined a table called "projects_students" though, which i think should work. 我定义了一个名为“ projects_students”的表,我认为该表应该有效。 I don't want to have a "project_users" table because the table is only for students, not for employers. 我不想有“ project_users”表,因为该表仅适用于学生,不适用于雇主。 How do I fix this? 我该如何解决? Here are my models: 这是我的模型:

class Student < User
    has_and_belongs_to_many :projects
end

- --

class Project < ActiveRecord::Base
    has_and_belongs_to_many :students
end

You are building @my_projects from a starting context of a User object. 您正在从User对象的起始上下文中构建@my_projects If you run User.first.projects and Student.first.projects from the Rails console, you will see that one tries to use projects_users as the join table and the other tries to use projects_students . 如果从Rails控制台运行User.first.projectsStudent.first.projects ,您将看到一个尝试将projects_users用作User.first.projects表,另一个尝试使用projects_students So rather than force a special "join_table" name in the model as I had suggested originally you could do something like this when you look up the projects: 因此,不必像我最初建议的那样在模型中强制使用特殊的“ join_table”名称,而是可以在查找项目时执行以下操作:

@my_projects = current_user.becomes(Student).projects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM