[英]Efficent way to select belongs_to model from another Model, in Rails 5?
[英]rails - Can't access a model that belongs_to another model
我有2個模型:項目和進度表。 項目has_one Schedule和Schedule Schedule_to項目。 創建項目后,該項目中涉及的一名員工最終將創建時間表。 我正在嘗試創建一個頁面,該頁面顯示雇主所有有時間表的項目。 在時間表控制器中,我嘗試了以下代碼:
def show_incomplete_schedules_to_employers
@schedules = Schedule.where("project.employer_id = ?", current_user.id).all
@projects = @schedules.collect{|schedule| schedule.project}
end
但這會返回錯誤:
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "project"
LINE 1: SELECT "schedules".* FROM "schedules" WHERE (project.employ...
^
: SELECT "schedules".* FROM "schedules" WHERE (project.employer_id = 32)):
app/controllers/schedules_controller.rb:174:in `show_incomplete_schedules_to_employers'
如何訪問雇主時間表?
您應該將此添加到您的雇主模型中:
has_many :schedules, through: :projects
然后訪問它:
current_user.employer.schedules
您同時需要@projects
和@schedules
做什么?
根據我想您正在嘗試做的事情,我將使用聯接來解決此問題。 像這樣:
def show_incomplete_schedules_to_employers
@schedules = Schedule.joins(:projects).where("projects.employer_id = ?", current_user.id)
@projects = @schedules.collect{ |schedule| schedule.project }
end
where
子句中projects
的復數形式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.