2011-08-06 148 views
2

下面是我的index.html.erb(我只是想展現品牌的名單和相關Subbrands)未定義的方法

<h1>Brands</h1> 

<% @brands.each do |brand| %> 
<h2><%= brand.name %></h2> 
<% end %> 

<% @brands.subbrands.each do |subbrand| %> 
<h2><%= subbrand.name %></h2> 
<% end %> 

我收到的時候觀看的index.html是錯誤:

undefined method `subbrands' for #<Array:0x9e408b4> 

這裏是我的brands_controller:

class BrandsController < ApplicationController 

def index 
    @brands = Brand.all 

    respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @brands } 
    end 
end 

end 

這裏是我的routes.rb

Arbitrary::Application.routes.draw do 

resources :brands do 
    resources :subbrands 
    end 

resources :subbrands do 
    resources :subsubbrands 
    end 

這裏是我的brand.rb模型

class Brand < ActiveRecord::Base 
    validates :name, :presence => true 

    has_many :subbrands 
    has_many :subsubbrands, :through => :subrands 
end 

...我subbrand.rb模型

class Subbrand < ActiveRecord::Base 
    validates :name, :presence => true 

    belongs_to :brand 
    has_many :subsubbrands 
end 

回答

5

你說這樣的:

@brands = Brand.all 

這意味着那@brands現在是一個數組,因爲all

A convenience wrapper for find(:all, *args) .

而且find(:all)

Find all - This will return all the records matched by the options used. If no records are found, an empty array is returned. Use Model.find(:all, *args) or its shortcut Model.all(*args) .

然後你有這樣的:

<% @brands.subbrands.each do |subbrand| %> 

和產生這個錯誤:

undefined method `subbrands' for #<Array:0x9e408b4> 

因爲@brands是一個數組,數組唐不知道subbrands的意思。像這樣的東西可能會更好地工作:

<% @brands.each do |brand| %> 
    <% brand.subbrands.each do |subbrand| %> 
     <h2><%= subbrand.name %></h2> 
    <% end %> 
<% end %> 

但你可能想要做的brand太多的東西。

+0

當我更改爲: – Abram

+0

謝謝你。當我修改index.html以包含您的建議時,我收到了另一個錯誤:未定義的方法'each'for# Abram

+0

@Abram:對不起,我省略'brand'和'each'之間的「子品牌」,請參閱我的更新。 –