【问题标题】:rails - Can't access a model that belongs_to another modelrails - 无法访问属于另一个模型的模型
【发布时间】:2014-02-05 19:11:29
【问题描述】:

我有 2 个模型:项目和计划。项目 has_one Schedule 和 Schedule belongs_to project。创建项目后,参与该项目的员工之一最终将创建一个时间表。我正在尝试创建一个页面,显示 雇主 他/她的所有有时间表的项目。在时间表控制器中,我尝试了以下代码:

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'

我如何访问雇主的日程安排?

【问题讨论】:

  • 错误是说在你的Schedule.where("project.employer_id = ?", current_user.id).all 中没有调用project 的表...语句中应该引用的“项目”是什么?跨度>
  • 所有计划都属于_一个项目。
  • 对,但这不是你的第二个声明@projects = ... 正在做的吗?
  • 我需要告诉第二条语句选择哪个时间表。在这种情况下,我想要所有 current_user(雇主)时间表。
  • 那么您要在哪个表上搜索employee_id?时间表?

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord


【解决方案1】:

您应该将其添加到您的 Employer 模型中:

has_many :schedules, through: :projects

然后访问它:

current_user.employer.schedules

@projects 和 @schedules 你需要什么?

【讨论】:

  • 我认为这行不通,因为项目需要有一个 schedule_id 列,这是没有意义的。我有“@schedules”和“@projects”,因为我需要在视图中访问包含时间表的项目。
  • 哦,我应该提到“雇主”是一种用户,所以 current_user = 雇主(至少在这里)
  • 啊,那么就使用 current_user.schedules - has_many :through 不关心foreign_key 的放置位置,只要定义了传递给through 的关联名称,它就会起作用。
  • 非常感谢 Broisatse
【解决方案2】:

据我推测您正在尝试做的事情,我会使用连接来解决这个问题。像这样的:

def show_incomplete_schedules_to_employers
  @schedules = Schedule.joins(:projects).where("projects.employer_id = ?", current_user.id)
  @projects = @schedules.collect{ |schedule| schedule.project }
end
  • 注意projects 在where 子句中的复数形式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多