导轨 - 包括动态条件协会 [英] Rails - Including associations with dynamic conditions
问题描述
由于学校的模式,并具有的has_many关系到学生的学生模型与学校:
Given a school model and a student model with the school having a has_many relation to student:
has_many :students, :conditions => proc { "year_id=#{send(:active_year_id)}" }
在这里active_year_id是在学校的模型中定义的方法,我遇到一个错误,active_year_id是不确定的打电话时:
where active_year_id is a method defined in the school model, I'm encountering an error that "active_year_id is undefined" when calling:
School.where(:active => true).includes(:students)
条件正常工作时,我做的,比方说,
The condition works fine when I do, say,
School.where(:id => 10).students
只有当我尝试使用包括做我得到这个错误。那是正确的行为。如果不是,有什么我做错了,我如何修复?
Only when I try to use includes do I get that error. Is that the right behavior. If not, what am I doing wrong and how do I fix ?
使用Rails 3.0.9,REE 1.8.7。
Using Rails 3.0.9, REE 1.8.7.
推荐答案
这是一个有点老了,但我看到的问题很多,也没有看到任何满意的解决方案。添加这样的条件基本上等同于创建一个协会有两个公钥/私钥。
This is a bit old, but I see the question a lot and have not seen any satisfactory solutions. Adding a condition like this is essentially equivalent to creating an association with two public/private keys.
@Fabio说得很的在执行PROC取决于它如何被称为是不同的上下文。的不过我认为你可以克服active_year_id是不确定的的问题。
@Fabio is right in saying "the context in where the proc is executed is different depending of how it's called." However I think you can overcome the "active_year_id is undefined" problem.
在这个例子:
class School < ActiveRecord::Base
has_many :students, :conditions => proc { "year_id=#{send(:active_year_id)}" }
...
的问题是,在某些情况下,在proc是在一个特定的校对象的上下文中执行,有时作为一个ActiveRecord ::协会:: JoinDependency :: JoinAssociation。我使用的是稍微复杂一点的进程内,这样解决了这个:
the issue is that in some situations, the proc is executed in the context of a particular School object and sometimes as an ActiveRecord::Associations::JoinDependency::JoinAssociation. I solved this using a slightly more complicated proc, like this:
class School < ActiveRecord::Base
has_many :students, :conditions => proc {
self.respond_to?(:active_year_id) ?
{year_id: self.active_year_id} :
'students.year_id = schools.active_year_id'
}
所以,当条件计算出实际的学校对象,自响应active_year_id属性访问器,你可以提供一个哈希值作为条件(其作品更漂亮不仅仅是一个插字符串创建关联的对象,等等。)
So, when the condition is calculated for an actual school object, self responds to the active_year_id attribute accessor and you can provide a hash as the condition (which works more nicely than just an interpolated string for creating associated objects, etc.)
在上下文中没有present 自作为一个实际的校对象,(正如你提到的,发生时使用的包含条款,例如被称为,)上下文是使用的字段名称,而不是值JoinAssociation和条件的字符串形式的作品就好了。
When the context does not present self as an actual school object, (which, as you noted, occurs when called using an include clause, for example,) the context is a JoinAssociation and the string form of the condition works just fine using field names rather than values.
我们发现这个解决方案让我们成功地使用动态关联。
We found this solution let us use the dynamic association successfully.
这篇关于导轨 - 包括动态条件协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!