我的模型中有以下代码:
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
中有一些字段,我想要访问特定的Investor
和Investment
。例如,像这样:
investor.investments.first.investment_data
它出错了:
NoMethodError undefined method 'investment_data' for #<Investment:0x000000070f3028>
其中investment_data
是连接InvestmentData
和investor
记录的investments.first
记录。
如何使用ActiveRecord
实现此目的?或者我应该使用原始SQL?
答案 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