我有一個關係模型,在這個模型中,學生和僱主可以在申請項目時進入關係。下面是型號:爲什麼我的has_one數據庫關係在rails中不起作用?
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
國家是在被自動設置爲「發佈」的項目表中的列。我試圖顯示所有的關係,有一個項目與狀態==:發佈。這裏是我的視圖代碼:
<% @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列。我的代碼應該從關係中找到項目,然後找到狀態列。我有關係has_one:項目,但我沒有:項目belongs_to關係,因爲項目不需要關係才能存在。我很確定我的數據庫關係是正確的。如何修復我的視圖代碼?或者,如果我的數據庫關係錯了,怎麼了?
更新 我忘了提及,僱主和學生都是用戶模型通過多態關聯。用戶模型有一個類型列,可以是Student或Employer。
嗯,這個問題雖然是有很多關係,每個人都可以有相同的項目。 – Philip7899
然後你的關係應該'belongs_to:project',你的項目應該'has_many:relationships'。 –