ruby-on-rails - Rails,ActiveRecord:列名匹配的 has_one
问题描述
我有一个关联,project has_many steps
我想在其中step
找到project
. 该project
表存储一个current_step
值,该值是step.name
当前step
.
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 关联,因此我可以优化加载current_step
并project
避免出现n+1
问题。
但是,我不断收到错误消息:
ActiveRecord::StatementInvalid: TinyTds::Error: The multi-part identifier "projects.step_name" could not be bound.
我做了一些查看 SO 并看到其他人遇到了这个 TinyTds 错误,但我不完全确定它的含义或它与我的特定情况有何关系。
如何选择current_step
这样可以有效地避免n+1
?
解决方案
你并没有真正的has_one
协会,你有一个特殊的成员,has_many
所以我会这样表达。关联的扩展方法steps
可以让你做到这一点:
has_many :steps do
def current
project = proxy_association.owner
find_by(name: project.step_name)
end
end
ActiveRecord 为关联设置的proxy_association
允许您回溯到包含project
as proxy_association.owner
。扩展方法的find_by
内部将被限定为关联。
然后你可以这样说:
project.steps.current
得到你期望你has_one
做的事情。
推荐阅读
- maven - gradle init 不适用于 pom.xml 中的某些插件
- c# - 有没有办法使用 C# 逐步执行 Windows Workflow Foundation?
- sas - 在 SAS 中绘制图形的一般语法
- sql - 将三个odoo(postgreSQL)数据库合并到一个数据库中
- javascript - React - Axios 承诺待定值未定义
- c# - MongoDB BSON(C# 驱动程序),如何反序列化使用 BsonDocument.ToJson() 序列化的 BSON 对象?
- c# - 使用 C# 我想创建一个条形图,显示 excel 列中每个值的计数
- oauth-2.0 - 存储在数据库中的 Json Web 令牌和验证
- angular - 使用 Msal 对 Angular 中的 Azure 广告进行身份验证
- python - 无缓冲的python覆盖率