2013-06-13 30 views
0

我花了最近三个小时试图找到一个解决方案,并检查了一切,我可以在这里找到StackOverflow,但没有去。BlogsController中的NoMethodError#create

我特别收到此错误:"undefined method []”为无:NilClass“`

和应用程序跟踪给了我这样的:app/controllers/blogs_controller.rb:7:in create'`

我认为这是与如何我传递的PARAMS,但我无法弄清楚什么是错这里是我的控制器代码:

class BlogsController < ApplicationController 
def index 
    @blogs = Blog.all 
end 

def new 
    @blog_entry = Blog.new 
end 

def create 
    Blog.create(title: params[:blogs][:title], content: params[:blogs][:content]) 
    redirect_to action: 'index' 
end 
end 

这是我的new.html.erb文件:

<%= form_for @blog_entry, as: :post, url: {action: "create"} do |f| %> 
    Title: </br> 
    <%= f.text_field :title %> <br /> 
    Content: <br /> 
    <%= f.text_area :content %> <br /> 
    <%= f.submit "Publish", class: "btn btn-primary" %> <br /> 
<% end %> 

下面是相关的日志文件:

Started POST "/blogs" for 127.0.0.1 at 2013-06-12 21:54:48 -0700 
Processing by BlogsController#create as HTML 
    Parameters: {"utf8"=>"✓",  "authenticity_token"=>"cSGH7PgbbFHSSEPV3pJ2LP6V1GvUN10RHRfUDTUXou4=", "post"=>{"title"=>"first  entry 5", "content"=>"new entry"}, "commit"=>"Publish"} 
    [1m[35m (0.1ms)[0m begin transaction 
    [1m[36mSQL (0.5ms)[0m [1mINSERT INTO "blogs" ("content", "created_at", "title",  "updated_at") VALUES (?, ?, ?, ?)[0m [["content", nil], ["created_at", Thu, 13 Jun 2013  04:54:48 UTC +00:00], ["title", nil], ["updated_at", Thu, 13 Jun 2013 04:54:48 UTC +00:00]] 
    [1m[35m (3.2ms)[0m commit transaction 
Redirected to http://localhost:3000/blogs 
Completed 302 Found in 5ms (ActiveRecord: 3.7ms) 

希望有人有一个想法。请?

回答

1

这应该这样做:

def create 
    Blog.create(params[:blog]) 
    redirect_to action: 'index' 
end 

让我知道,如果它不是。我会尝试修改我的答案,并在此处粘贴完整的错误跟踪以防万一不起作用。控制台登录过,因为你在新的动作初始化@blog_entry您可能需要创建博客与Blog.create(params[:blog_entry])

编辑

从控制台"post"=>{"title"=>"first entry 5", "content"=>"new entry"}

意味着你需要创建一个博客条目与:Blog.create(params[:post])

+0

不,不幸的是,这也不起作用。我没有收到任何错误,但是它创建了一个记录,其中的字段值为零。 –

+0

我也曾尝试使用Blog.create(params {:blog_entry])具有相同的零结果。 –

+0

请按控制台日志,在你点按提交按钮 – rmagnum2002

相关问题