当我尝试通过我的Lecture控制器的创建方法创建“Lecture”时,我收到此错误。这曾经工作,但我继续在应用程序的其他部分工作当然,我回来了&当用户试图在我的应用程序中创建一个Lecture时,某些东西现在会抛出此错误。
我确定它的东西很小我只是在俯视(已经过了一段时间而且可能需要休息一下)...但是如果有人能让我知道为什么会这样,我会很感激..我知道如果我需要发布任何其他内容...... thx!
我得到的错误
NoMethodError in LecturesController#create
undefined method `save' for nil:NilClass
Rails.root: /Users/name/Sites/rails_projects/app_name
Application Trace | Framework Trace | Full Trace
app/controllers/lectures_controller.rb:13:in `create'
我想创建一个新的讲座
视图/讲座/ new.html.erb
<% provide(:title, 'Start a Lecture') %>
<div class="container">
<div class="content-wrapper">
<h1>Create a Lecture</h1>
<div class="row">
<div class="span 6 offset3">
<%= form_for(@lecture) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.text_field :title, :placeholder => "What will this Lecture be named?" %>
<%= f.text_area :content, :placeholder => "Describe this Lecture & what will be learned..." %>
</div>
<%= f.submit "Create this Lecture", :class => "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
</div>
</div>
然后我的控制器说错误来自
控制器/ lectures_controller.rb
class LecturesController < ApplicationController
before_filter :signed_in_user, :only => [:create, :destroy]
before_filter :correct_user, :only => :destroy
def index
end
def new
@lecture = current_user.lectures.build if signed_in?
end
def create
if @lecture.save
flash[:success] = "Lecture created!"
redirect_to @lecture
else
@activity_items = [ ]
render 'new'
end
end
def show
@lecture = Lecture.find(params[:id])
end
def destroy
@lecture.destroy
redirect_to root_path
end
private
def correct_user
@lecture = current_user.lectures.find_by_id(params[:id])
redirect_to root_path if @lecture.nil?
end
答案 0 :(得分:1)
您依靠before过滤器为后续操作设置实例变量。这不起作用。您必须在需要它的控制器操作中明确设置它。过滤器之前的唯一目的是过滤哪些操作运行,哪些不运行。
编辑:我误读了你的代码。我以为你在创建动作之前运行了correct_user。无论哪种方式,很高兴知道它现在有效!