【发布时间】:2018-12-10 14:25:47
【问题描述】:
我有 2 个这样的模型:
Account - has 2 columns account_id and account_name
MonthForecast - has 3 columns - account_id, entity and report_key
我在Account 中定义了has_many :month_forecasts,在MonthForecast 中定义了belongs_to :account
我正在使用这样的includes:
@months = Account.includes(:month_forecasts)
当我进行这样的迭代时:
@months.each do |forecast|
case forecast.month_forecasts.report_key
,我在上面的case 语句中收到此错误:
undefined method `report_key' for #<ActiveRecord::Associations::CollectionProxy []>
我该如何解决这个问题?
【问题讨论】:
-
month_forecasts是一个集合,它没有report_key属性。你应该遍历它,例如:forecast.month_forecasts.each... -
如果我以这种方式进行迭代,我是否能够从每一行的两个模型中访问所有字段?
-
当然,试一试
-
这就像一个魅力!非常感谢!
标签: ruby-on-rails join model