0

我有 3 个模型:

Tiersets
  has_many Tiers

Tiers
  belongs_to Tierset
  has_and_belongs_to_many Features

Feature
  has_and_belongs_to_many Tiers

Feature中,我有一个String名为的列Feature_Code,其中包含以下字符串之一:“ F_VIZ”、“ F_DATA”、“ F_SCORE”。

我正在尝试构建一个查询,以在已知Tierset的所有Feature对象中查找所有具有该代码F_VIZTier对象Tierset

我在 AREL 查询中尝试了一堆 :includes 的组合,但我显然对表的连接方式感到困惑。任何帮助深表感谢。

4

1 回答 1

1

The SQL you want is

select * from features, features_tiers, tiers where features_tiers.id = features.id and features_tiers.tier_id = tiers.id and features.code = 'F_VIZ' AND tierset_id = ?;

so we'll translate this directly to ActiveRecord:

Feature.joins(:tiers).where(:code => 'F_VIZ', 'tiers.tierset_id' => 1)

Which is a bit cleaner, since AR 'knows' about the implicit join table between features and tiers based on how your associations are set up.

于 2013-03-11T04:42:25.560 回答