Dave Olson
Dave Olson

Reputation: 252

NoMethodError in BlogsController#create

I've spent the last three hours trying to find a solution to this and checked everything I could find here on StackOverflow but no go.

I am specifically getting this error: "undefined method[]' for nil:NilClass"`

And the application trace gives me this: app/controllers/blogs_controller.rb:7:increate'`

I think it has something to do with how I am passing the params but I can't figure out what's wrong. Here's my Controller code:

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

Here's my new.html.erb file:

<%= 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 %>

Here's the relevant log file:

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)

Hopefully someone has an idea. Please?

Upvotes: 0

Views: 115

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

this should do it:

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

let me know if it's not. I'll try to revise my answer, and paste please the full error trace here in case it's not working. The console logs too, as you initialize @blog_entry in the new action you might need to create blog with Blog.create(params[:blog_entry])

EDIT

from console "post"=>{"title"=>"first entry 5", "content"=>"new entry"}

means you need to create a blog entry with: Blog.create(params[:post])

Upvotes: 1

Related Questions