在 Rails 4 中的视图中显示嵌套关联

Displaying nested association in view in Rails 4

我有以下3个模型:

class Kick < ActiveRecord::Base
 has_many :offs
 has_many :retailers, :through => :off
end

class Retailer < ActiveRecord::Base
 has_many :offs
 has_many :kicks, :through => :off
end

class Off < ActiveRecord::Base
 belongs_to :kicks
 belongs_to :retailers
end

我正在尝试在 'show Kick view' 中显示零售商的名称,如下所示:

  <% @kick.off.each do|off| %>
    <%= off.name %>
    <%= off.retailers.name %>
  <% end %>

Off.name 显示正常,但我似乎无法从此视图中索引零售商名称。我错过了什么?

错误:

undefined method `name' for nil:NilClass
class Kick < ActiveRecord::Base
 has_many :offs
 has_many :retailers, :through => :offs
end

class Retailer < ActiveRecord::Base
 has_many :offs
 has_many :kicks, :through => :offs
end

class Off < ActiveRecord::Base
 belongs_to :kick
 belongs_to :retailer
end


@kick = Kick.includes(:retailers => :offs).where('kicks.id' => 1).select('retailers.name, kicks.*')
class Kick < ActiveRecord::Base
 has_many :offs
 has_many :retailers, :through => :offs
end

class Retailer < ActiveRecord::Base
 has_many :offs
 has_many :kicks, :through => :offs
end

class Off < ActiveRecord::Base
 belongs_to :kick
 belongs_to :retailer
end

还要确保在数据库中正确索引了模型

在视图中应该是 kick.offs 而不是 kick.off

<% @kick.offs.each do|off| %>
    <%= off.name %>
    <%= off.retailers.name %>
  <% end %>