【发布时间】:2019-06-12 01:15:25
【问题描述】:
我有一个关联,其中 project has_many steps 和我想为 project 找到“当前”step。 project 表存储一个current_step 值,即当前step 的step.name。
class Project < ApplicationRecord
# attributes: step_name:string
has_many :steps
has_one :current_step, -> { where("steps.name = projects.step_name") }, class_name: "Step"
end
class Step < ApplicationRecord
# attributes: project_id:integer, name:string
belongs_to :project
end
我正在尝试将其设置为 ActiveRecord 关联,因此我可以使用project 优化加载current_step 并避免n+1 问题。
但是,我不断收到错误消息:
ActiveRecord::StatementInvalid: TinyTds::Error: The multi-part identifier "projects.step_name" could not be bound.
我在 SO 上做了一些查看,发现其他人遇到了这个 TinyTds 错误,但我不完全确定它的含义或它与我的特定情况有何关系。
如何选择current_step 以便可以有效地包含它以避免n+1?
【问题讨论】:
-
尝试在您的
where中添加.first -
尝试用
has_one :current_step, -> { joins(:steps).where("steps.name = ?", step_name) }, class_name: "Step"之类的东西定义has_one关系
标签: ruby-on-rails rails-activerecord tiny-tds