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

发布于 2025-01-06 07:43:31 字数 585 浏览 2 评论 0原文

我想知道是否有一种“正确的”Rails (3.1) 方法可以在不使用 finder SQL 的情况下执行此操作。

我有一个 STI 层次结构:

class Party
class Person < Party
class Organisation < Party

相关方通过 party_relationships 表和模型连接,并使用外键 party_id 和 related_pa​​rty_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枯寂 2025-01-13 07:43:31

解决了。这很有效,而且我不得不说,范围和关系的运作方式给我留下了深刻的印象:

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

现在,如果我有一个聚会……

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

我真正喜欢什么关于这一点是,如果我在 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:

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. This way keeps things properly encapsulated so that a Party doesn't have to know how the scope is implemented. Neat.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文