Reputation: 4677
I have a relationship model in which students and employers can enter into a relationship when applying to a project. Here are the models:
class Student < User
has_many :relationships, dependent: :destroy
has_many :employers, through: :relationships
end
class Employer < User
has_many :projects
has_many :relationships, dependent: :destroy
has_many :students, through: :relationships
end
class Relationship < ActiveRecord::Base
has_one :project
belongs_to :employer
belongs_to :student
validates_uniqueness_of :project_id, :scope => [:employer_id, :student_id]
end
class Project < ActiveRecord::Base
belongs_to :employer
end
State is a column in the projects table that is automatically set equal to 'posting'. I am trying to show all relationships that have a project with state == :posting. Here is my view code:
<% @relationships.each do |relationship| %>
<% if relationship.project.state == :posting %>
<%= relationship.project.inspect %>
<% end %>
<% end %>
Also, in the controller for this view is:
@relationships = Relationship.all
When i try to open the view, i get:
PG::UndefinedColumn: ERROR: column projects.relationship_id does not exist
What doesn't make sense to me is that I am not looking in the projects table for a relationship_id column. My code should find the project from the relationship and then find the state column. I have relationships has_one :project but i don't have :projects belongs_to relationships because a project does not need a relationship in order to exist. I'm pretty sure my database relations are right. How do I fix my view code? Or, if my db relationships are wrong, what's wrong?
Update i forgot to mention that Employer and Student are both User models through polymorphic association. The user model has a type column that can be either Student or Employer.
Upvotes: 0
Views: 1900
Reputation: 29429
When you declare that Relationship
has_one :project
, you are telling Rails that the Project
model (and the corresponding projects
database table) has a relationship_id
field . When you refer to relationship.project
in your view, you cause that table/field to be referenced, resulting in your error.
Given that each relationship should indeed have just one project associated with it, you should declare Project
as belongs_to :relationship
, create the appropriate migration and update your code accordingly to maintain the value of this field.
Upvotes: 3
Reputation: 158
At first glance it seems like it should be
class Employer < User
has_many :projects, through: :relationships
for this to work. Am I missing something?
Upvotes: 0