根据连接表中的条件获取Rails连接模型记录
我想知道是否有一种“正确的”Rails (3.1) 方法可以在不使用 finder SQL 的情况下执行此操作。
我有一个 STI 层次结构:
class Party
class Person < Party
class Organisation < Party
相关方通过 party_relationships 表和模型连接,并使用外键 party_id 和 related_party_id
我想要做的是:
class Party
# Should return all party_relationships where the related_party is a Person
has_many :person_relationships
# Should return all party_relationships where the related_party is an Organisation
has_many :organisation_relationships
end
在 Rails 3.1 中执行此操作的最佳方法是什么?
I'm wondering if there's a "proper" Rails (3.1) way to do this without just using a finder SQL.
I have an STI hierarchy:
class Party
class Person < Party
class Organisation < Party
Related parties are joined via a party_relationships table and model, with foreign keys party_id and related_party_id
I want to be able to do is this:
class Party
# Should return all party_relationships where the related_party is a Person
has_many :person_relationships
# Should return all party_relationships where the related_party is an Organisation
has_many :organisation_relationships
end
What's the best way of doing this in Rails 3.1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了。这很有效,而且我不得不说,范围和关系的运作方式给我留下了深刻的印象:
现在,如果我有一个聚会……
我真正喜欢什么关于这一点是,如果我在 has_many 上使用 :finder_sql 那么 SQL 将位于 Party 类中。这种方式可以正确封装事物,以便参与方不必知道范围是如何实现的。整洁的。
Solved it. This works, and I have to say that I'm very impressed with the way the scopes and relationships work:
Now if I have a party...
What I really like about this is that if I'd used :finder_sql on a has_many then the SQL would be in the Party class. This way keeps things properly encapsulated so that a Party doesn't have to know how the scope is implemented. Neat.