2015-06-04 37 views
0

我有3种型号如下:显示,鉴于嵌套的关联轨道4,5

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 

而且我想在我的“表演踢视图”显示零售商的名称如下:

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

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

错误:

undefined method `name' for nil:NilClass 
+0

它应该是'<%@ kick.offs.each做| f |%>' –

回答

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 

也确保你正确索引在数据库

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

它适合你吗? –

0

模型在视图应该kick.offskick.off

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