dsp_099
dsp_099

Reputation: 6121

Why doesn't this work? (More so Ruby than Rails)

def refresh_menu
    @menu_pages = []

    $menu_items.each do |id|
        @menu_pages[id - 1] = Page.find(id)
    end
end

$menu_items is just an array [1,2]. Obviously what I want to do is populate @menu_pages with all the pages found as per $menu_items.

Mind you,

@menu_pages = Page.all

works just fine. So how come I can't add them one-by-one with Page.find(id)?

The error returned:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each

Upvotes: 2

Views: 119

Answers (3)

dsp_099
dsp_099

Reputation: 6121

nowk, thanks for the neat trick.

To those who might find this through search: don't forget to restart the server when you make changes to initializers.

Upvotes: 4

nowk
nowk

Reputation: 33161

Why not just do?...

def refresh_menu
  @menu_pages = Page.where(:id => $menu_items)
end

And in relation to the error, where is $menu_items defined?

Upvotes: 5

Chris Bunch
Chris Bunch

Reputation: 89803

Where are you defining $menu_items? From your error message, it looks like the refresh_menu method can't see it - and thus thinks it's nil.

Upvotes: 0

Related Questions