vendredi 5 mai 2017

Way to add links to pages dynamically in ruby on rails

My pages controller has this code:

class PagesController < ApplicationController

def index
    @pages = Page.all
end

def new
    @page = Page.new
end

def edit
    @page = Page.find(params[:id])
end

def create
    @page = Page.new(page_params)
    @page.save
    redirect_to @page
end

def update
    @page = Page.find(params[:id])
    @page.update(page_params)
    redirect_to @page
end

def show
    @page = Page.find(params[:id])
end

def destroy
    @page = Page.find(params[:id])
    @page.destroy
    redirect_to pages_path
end


private
def page_params
    params.require(:page).permit(:title,:description)
end

end

And in my navbar I have this code:

<% @pages.each do |page| %>
        <li?<%= link_to 'page.title', page_path(page)%></li>
    <% end %>

The code should generate the titles of each page created. However I get the following error when I run the page:

undefined method `each' for nil:NilClass

Now I thought I had eliminated this issue by entering the code inside the new function in PagesController. This pages controller is just for additional pages. The navbar also contains links to static pages. So there should always be some value in the navbar.

Has anybody any advice?

Aucun commentaire:

Enregistrer un commentaire