Rails的包括()不使用动态关联的条件下工作 [英] Rails' includes() doesn't work with dynamic association conditions
问题描述
工作在一个多租户应用程序,其中大多数我的车型将有一个tenant_id场这样我就可以确保读取权限,通过该协会发现( current_tenant.applications.find(PARAMS [:ID])
):
Working on a multi-tenant app where most of my models will have a tenant_id field so I can ensure read permissions by finding through the association (current_tenant.applications.find(params[:id])
):
class Application < ActiveRecord::Base
belongs_to :tenant
has_many :app_questions, :conditions => proc {{:tenant_id => tenant_id}}, :dependent => :destroy
end
我喜欢这让我优雅地创建一个新的AppQuestion与tenant_id自动设置:
I like how this allows me to elegantly create a new AppQuestion with the tenant_id set automatically:
@application = current_tenant.applications.find(params[:app_question][:application_id])
@question = @application.app_questions.build(params[:app_question])
#...
但问题是,当我尝试用包括()
来渴望加载它抛出一个错误的关联:
Problem is, when I try to use includes()
to eager-load the association it throws an error:
current_tenant.applications.where(:id => params[:id]).includes(:app_questions => :app_choices).first
NoMethodError (undefined method `tenant_id' for #<Class:0x007fbffd4a9420>):
app/models/application.rb:7:in `block in <class:Application>'
我可以重构,这样我就不必在联想条件在proc,但我想知道如果任何人有一个更好的解决方案。
I could refactor so that I don't have to have the proc in the association conditions, but am wondering if anyone has a better solution.
裁判不说:如果你需要以动态评估条件运行时,使用一个进程
The ref does say: "If you need to evaluate conditions dynamically at runtime, use a proc"
推荐答案
我已经回答了更多的细节,试图解释为什么这不能工作的另一个问题。
I've replied to the other question with more details trying to explain why this cannot work.
当他们说动是因为在proc可以在运行时执行,但不可以的应用程序的现有实例的情况下
类因为当你调用这个关系不存在
When they say dynamic is because the proc can be executed at runtime, but not in the context of an existing instance of the Application
class because it doesn't exist when you invoke this relation
Application.where(:id => params[:id]).includes(:app_questions => :app_choices)
这篇关于Rails的包括()不使用动态关联的条件下工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!