Abram
Abram

Reputation: 41884

Undefined method

Below is my index.html.erb (I just want to show a list of Brands and associated Subbrands)

<h1>Brands</h1>

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

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

The error I receive when viewing index.html is:

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

Here is my 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

Here is my routes.rb

Arbitrary::Application.routes.draw do

resources :brands do
  resources :subbrands 
  end

resources :subbrands do
   resources :subsubbrands
  end

Here is my brand.rb model

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

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

...and my subbrand.rb model

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

    belongs_to :brand
    has_many :subsubbrands
end

Upvotes: 2

Views: 368

Answers (1)

mu is too short
mu is too short

Reputation: 434665

You're saying this:

@brands = Brand.all

That means that @brands is now an Array because all:

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

And 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).

Then you have this:

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

And that produces this error:

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

Because @brands is an Array and Arrays don't know what subbrands means. Something like this might work better:

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

But you probably want to do something with the brand too.

Upvotes: 5

Related Questions