2015-06-04 71 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 %>