0

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. 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. I don't want to have a "project_users" table because the table is only for students, not for employers. 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
tereško
  • 58,060
  • 25
  • 98
  • 150
Philip7899
  • 4,599
  • 4
  • 55
  • 114

1 Answers1

0

You are building @my_projects from a starting context of a User object. 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. 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:

@my_projects = current_user.becomes(Student).projects
cschroed
  • 6,304
  • 6
  • 42
  • 56
  • Thanks, it works. But is this a bad practice? Shouldn't it automatically know the join table? Also, for some reason when the join table is created the student_id is not being passed into it. – Philip7899 Nov 15 '13 at 15:19
  • OK, now I see the real issue. I've updated my answer to offer another suggestion that avoids explicitly defining a join_table name in the model. – cschroed Nov 15 '13 at 17:40