我一直在寻找几个小时,但我无法在任何地方找到答案。我是 ruby on rails 的新手,我不知道如何解决这个问题。导致问题的原因是我将一个实例变量从一个文件移动到另一个文件,现在没有链接正在工作,并且错误总是显示:undefined method `each' for nil:NilClass
这是我的代码:
应用程序.html.erb:
<% number = 1 %>
<% @projects.each do |project| %>
<%= link_to project, id: "a-#{number}" do %>
<div class="flex">
<div class="each--project" id="project-<%= number %>">
<h3><%= project.title %></h3>
<p class="date"><%= project.created_at.strftime("%A, %b %d")%></p>
<p class="content"><%= project.description %></p>
</div>
</div>
<% number = number + 1 %>
<% end %>
<% end %>
application_controller.rb
class ApplicationController < ActionController::Base
def index
@projects = Project.all
end
protect_from_forgery with: :exception
end
项目_控制器
class ProjectsController < ApplicationController
before_action :find_project, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@projects = Project.all.order("created_at desc")
end
def new
@project = Project.new
end
def create
@project = Project.new project_params
if @project.save
redirect_to @project, notice: "Yay Mia! That project was saved!"
else
render 'new'
end
end
def show
end
def edit
end
def update
if @project.update project_params
redirect_to @project, notice: "Yay Mia! That project was updated!"
else
render 'edit'
end
end
def destroy
@project.destroy
redirect_to projects_path
end
private
def find_project
@project = Project.friendly.find(params[:id])
end
def project_params
params.require(:project).permit(:title, :description, :link, :slug)
end
end
路线 rb
Rails.application.routes.draw do
devise_for :users
resources :posts
resources :projects
resources :contacts, only: [:new, :create]
get 'welcome/index'
root 'welcome#index'
get '*path' => redirect('/')
end