精确的关联记录与has_many通过

时间:2016-03-22 15:32:03

标签: ruby-on-rails ruby activerecord

我的模型中有以下代码:

class Investment < ActiveRecord::Base
  has_many :investment_datas
  has_many :investors, through: :investment_datas, source: :investor

class Investor < ActiveRecord::Base
  has_many :investment_datas
  has_many :investments, through: :investment_datas, source: :investment

class InvestmentData < ActiveRecord::Base
  belongs_to :investor
  belongs_to :investment

我在InvestmentData中有一些字段,我想要访问特定的InvestorInvestment。例如,像这样:

investor.investments.first.investment_data

它出错了:

NoMethodError undefined method 'investment_data' for #<Investment:0x000000070f3028>

其中investment_data是连接InvestmentDatainvestor记录的investments.first记录。

如何使用ActiveRecord实现此目的?或者我应该使用原始SQL?

1 个答案:

答案 0 :(得分:0)

你说:

  

其中investment_data是连接投资者和投资的投资数据记录。第一个记录。

然后你可以这样做:

InvestmentData.where(investor_id: investor.id, investment_id: investments.first.id).first
# or
investor.investment_datas.where(investment_id: investments.first.id).first
# or
investments.first.investment_datas.where(investor_id: investor.id).first