Bikal
Bikal

Reputation: 33

NoMethodError in PostsController#create undefined method `body'

Whenever I try to save the post, this error is showing up.

Image

Here's my new.html.erb file.

<div id="page_wrapper">
 <h1>New Post</h1>
  <%= form_for :post, url: posts_path do |f| %>
  <% if @post.errors.any? %>
  <div id="errors">
    <h2><%= pluralize(@post.errors.count, "error") %> prevented this post from saving:</h2>
    <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>
<p>
  <%= f.label :title %><br>
  <%= f.text_field :title %><br>
</p>

<p>
  <%= f.label :date %><br>
  <%= f.text_field :date %><br>
</p>

<p>
  <%= f.label :time %><br>
  <%= f.text_field :time %><br>
</p>

<p>
  <%= f.label :location %><br>
  <%= f.text_field :location %><br>
</p>

<p>
  <%= f.submit %>
</p>
<% end %>
</div> 

Here's my show.html.erb file.

<div id="page_wrapper">
<h1 class="title">
    <%= @post.title %>
</h1>

<p class="date">
    Submitted <%= time_ago_in_words(@post.created_at) %> Ago
</p>

<p class="time">
    <%= @post.time %>
</p>

<p class="location">
    <%= @post.location %>
</p>
</div>

Here's my posts_controller.rb file.

class PostsController < ApplicationController
 def index
    @posts = Post.all.order('created_at DESC')      
 end

 def new    
    @post = Post.new    
 end

 def create
    @post = Post.new(post_params)

    if @post.save   
        redirect_to @post
    else
        render 'new'
    end
 end

 def show
    @post = Post.find(params[:id])      
 end

 private
 def post_params
    params.require(:post).permit(:title, :body, :location)
 end
end

Hers's my routes.rb file

 Rails.application.routes.draw do
  resources :posts
  root "posts#index"
 end

Upvotes: 1

Views: 1096

Answers (2)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

You have added a validation for body in your post.rb. But you don't have the field body in your posts table.

So, when @post.create is invoked, all the validations defined in post.rb are run and since you don't have a body field, you were getting an Undefined method 'body' for Post error.

To solve it, remove the validation for body in post.rb

Remove the following line

validates :body, presence: true

And you should be good to go.

Upvotes: 2

mrvncaragay
mrvncaragay

Reputation: 1260

params.require(:post).permit(:title, :body, :location)

You required :body but in your form you have title, date, time and location.

Remove it and make sure you have this attributes in your strong params like this:

params.require(:post).permit(:title, :date, :time, :location)

Upvotes: 0

Related Questions