【问题标题】:Why this error while using "includes" in Ruby on Rails为什么在 Ruby on Rails 中使用“包含”时出现此错误
【发布时间】: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


【解决方案1】:
@months.each do |loop1|
  loop1.each do |loop2|
    loop1.<fields in left table>
    loop2.<fields in right table>

这对我有用!感谢@peresleguine

【讨论】:

    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多