Home Ask Login Register

Developers Planet

Your answer is one click away!

Sebastian Delgado February 2016

How to show some posts options, only for the creator of the post in Rails

I'm getting the error "undefined method user' for nil:NilClass", but my code looks good to me. I checked from the Rails console, and the posts do have theuser_id` field and it works as expected.

This is my posts model:

# == Schema Information
# Table name: posts
#  id         :integer          not null, primary key
#  body       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  user_id    :integer

class Post < ActiveRecord::Base
    validates :body, presence: true
    belongs_to :user

This is my create action in my posts controller:

def create
        @post = Post.new(post_params)
        @post.user = current_user
        if @post.save
            redirect_to root_path
            render :new

This is the portion of my view where I try to "moderate" who has access to the edit and delete:

<% if signed_in? && @post.user == current_user %>

    <%= link_to "Edit", edit_post_path(post) %>
    <%= link_to "Delete", post, method: :delete, data: {confirm: "Are you sure you want to delete this post?"} %>

Here is the error trace:

Started GET "/" for ::1 at 2016-02-06 15:48:00 -0500
Processing by PostsController#index as HTML
  Post Load (0.3ms)  SELECT "posts".* FROM "posts"  ORDER BY "posts"."id" DESC
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Rendered posts/index.html.erb within layouts/application (9.2ms)
Completed 500 Internal Server Error in 46ms (ActiveRecord: 0.4ms)

ActionView::Template::Error (undefined method `user' for nil:NilClass):
     9:                     <div class="post-container hyphenate">
    10:                         <%= post.body %>
    12:                         <% if signed_in? && @        


spickermann February 2016


<% if signed_in? && @post.user == current_user %>


<% if signed_in? && post.user == current_user %>

There is no @post on the index page.

Post Status

Asked in February 2016
Viewed 2,127 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life