【问题标题】:Fetch Rails join model records based on condition in joined table根据连接表中的条件获取 Rails 连接模型记录
【发布时间】:2012-03-09 05:54:29
【问题描述】:

我想知道是否有一种“正确的”Rails (3.1) 方法可以在不使用查找器 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 中最好的方法是什么?

【问题讨论】:

    标签: ruby-on-rails associations has-many-through has-many scopes


    【解决方案1】:

    解决了。这很有效,我不得不说我非常对范围和关系的工作方式印象深刻:

    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 类中。这种方式可以使事情得到适当的封装,这样一方就不必知道范围是如何实现的。整洁。

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多