在Rails 4中显示嵌套关联

时间:2015-06-04 13:00:21

标签: ruby-on-rails associations model-associations

我有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

3 个答案:

答案 0 :(得分:0)

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.*')

答案 1 :(得分:0)

hdfs dfs -put

还要确保在db

中正确索引模型

答案 2 :(得分:0)

在视图中,它应为kick.offs而不是kick.off

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