2

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
0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this. When I modified the index.html to include your suggestion I received another error: undefined method `each' for #<Brand id: 1, name: "brand1", created_at: nil, updated_at: nil>
@Abram: Sorry, I left out the "subbrands" between brand and each, please see my update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.