簡體   English   中英

HABTM無法與Rails中的多態關聯一起使用

[英]HABTM not working with polymorphic association in rails

我有一個多態關聯:我的用戶模型可以是“學生”類型或“雇主”類型。 我正在嘗試在學生模型和另一個稱為“項目”模型的模型之間建立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

您正在從User對象的起始上下文中構建@my_projects 如果從Rails控制台運行User.first.projectsStudent.first.projects ,您將看到一個嘗試將projects_users用作User.first.projects表,另一個嘗試使用projects_students 因此,不必像我最初建議的那樣在模型中強制使用特殊的“ join_table”名稱,而是可以在查找項目時執行以下操作:

@my_projects = current_user.becomes(Student).projects

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM