ActiveRecord包含缺少记录的关联

时间:2013-05-06 09:06:12

标签: activerecord ruby-on-rails-3.2 associations

我正在进行以下查询

PortfolioDistribution.joins(:portfolio_distribution_split).
  select('policy_number, reinvestment_date, reinvestment_units,
  reinvestment_units, split_name, split_percentage').
  where(:policy_number => policy_no, :reinvestment_date => period,
  :ods_psgamas_gls_portfolio_distribution_split => { :split_name => type })

返回15条记录,但关联的模型portfolio_distribution_splitnil。如果我更改查询以包含关联模型,如下所示:

PortfolioDistribution.joins(:portfolio_distribution_split).
  select('policy_number, reinvestment_date, reinvestment_units,
  reinvestment_units, split_name, split_percentage').
  where(:policy_number => policy_no, :reinvestment_date => period,
  :ods_psgamas_gls_portfolio_distribution_split => { :split_name => type }).
  includes(:portfolio_distribution_split)

我只获得3条记录?如果我使用生成的SQL并直接对数据库运行它,我会得到15条记录。其他12条记录怎么了?

  • activemodel(3.2.13)
  • activerecord(3.2.13)
  • activerecord-sqlserver-adapter(3.2.8)
  • activeresource(3.2.13)
  • activesupport(3.2.13)

1 个答案:

答案 0 :(得分:0)

我的问题是遗产。

portfolio_distributionportfolio_distribution_split有一对多的关系。

当我运行第一个查询时,我会得到每个portfolio_distribution_split的记录。

第二个查询返回每个portfolio_distribution的记录,其中portfolio_distribution_splits数组与portfolio_distributions

相关联