나는 학생과 고용주가 프로젝트에 지원할 때 관계를 형성 할 수있는 관계 모델을 가지고있다. 다음은 모델입니다.왜 내 has_one 데이터베이스 관계가 레일에서 작동하지 않습니까?
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 == : posting을 가진 프로젝트가있는 모든 관계를 보여 주려고합니다. 여기 내보기 코드 :
<% @relationships.each do |relationship| %>
<% if relationship.project.state == :posting %>
<%= relationship.project.inspect %>
<% end %>
<% end %>
또한,이 뷰 컨트롤러 것은 : 내가보기를 열려고하면
@relationships = Relationship.all
, 내가 얻을 :
PG::UndefinedColumn: ERROR: column projects.relationship_id does not exist
아무튼 무엇 나에게 의미가 없다는 것은 내가 relationship_id 열에 대한 projects 테이블을보고 있지 않다는 것이다. 내 코드는 관계에서 프로젝트를 찾아 주 컬럼을 찾아야합니다. 나는 has_one : project하지만 have have : 관계가 존재하지 않기 때문에 관계가 필요하기 때문에 관계가 생겼다. 나는 내 데이터베이스 관계가 옳다는 것을 확신한다. 내보기 코드를 수정하려면 어떻게해야합니까? 또는 DB의 관계가 잘못 되었다면 무엇이 문제입니까?
업데이트 고용주와 학생 모두 다형성 연관을 통한 사용자 모델이라는 것을 잊어 버렸습니다. 사용자 모델에는 학생 또는 고용주가 될 수있는 유형 열이 있습니다. 그것은이 작동 할
class Employer < User
has_many :projects, through: :relationships
해야처럼
흠, 문제는 각각 서로 같은 프로젝트를 가질 수있는 관계가 많다는 것입니다. – Philip7899
그러면 관계가'belongs_to : project'이어야하고 프로젝트는'has_many : relationships'이어야합니다. –