0

在过去的三个小时里,我一直在试图找到解决方案,并检查了我在 StackOverflow 上可以找到的所有内容,但没有成功。

我特别收到此错误:"undefined method[]' for nil:NilClass"`

应用程序跟踪给了我这个:app/controllers/blogs_controller.rb:7:increate'`

我认为这与我传递参数的方式有关,但我不知道出了什么问题。这是我的控制器代码:

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)

希望有人有想法。请?

4

1 回答 1

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])

于 2013-06-13T04:28:36.980 回答