简体   繁体   English

根据联接表中的条件获取Rails联接模型记录

[英]Fetch Rails join model records based on condition in joined table

I'm wondering if there's a "proper" Rails (3.1) way to do this without just using a finder SQL. 我想知道是否有一种“正确的” Rails(3.1)方法,而不仅仅是使用finder SQL。

I have an STI hierarchy: 我有一个STI层次结构:

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 通过party_relationships表和模型将关联方与外键party_id和related_pa​​rty_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? 在Rails 3.1中执行此操作的最佳方法是什么?

Solved it. 解决了。 This works, and I have to say that I'm very impressed with the way the scopes and relationships work: 这工作,我不得不说,我深刻的印象,范围和关系的工作方式:

class Party
  has_many :party_relationships, foreign_key: :party_id
end

class PartyRelationship
  belongs_to :related_party, :class_name => 'Party'
  scope :to_organisations, :joins => :related_party, :conditions => {:parties => {:type => 'Organisation' } }
end

Now if I have a party... 现在如果我要参加一个聚会...

@party.party_relationships                   # <- returns all relationships
@party.party_relationships.to_organisations  # <- Only those where related_party is an organisation

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. 真正喜欢的是,如果在has_many上使用:finder_sql,那么该SQL将在Party类中。 This way keeps things properly encapsulated so that a Party doesn't have to know how the scope is implemented. 通过这种方式可以正确封装所有内容,从而使缔约方不必知道如何实现范围。 Neat. 整齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM