TheVic
TheVic

Reputation: 313

Current_user doesn't return a value

My current_user function does'nt work in my Post controller. When i try to show /posts/1, that is 1st record maded in dbconsole i recive this error:

Couldn't find Post with id=1 [WHERE "posts"."user_id" = ?]

See my sources: post model:

class Post < ActiveRecord::Base
    belongs_to :user
end

post model:

  class User < ActiveRecord::Base
  has_many :posts
  attr_accessor :password
  before_save :encrypt_password
  .....

application controller:

  class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  helper_method :current_user
      private
      def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
      end
  end

the problem appear only in post controller:

class PostsController < ApplicationController
...
    def show
    @post = current_user.posts.find(params[:id])
    end
...
end

Can onyone help me?

Upvotes: 0

Views: 124

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53018

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

The above will find posts belonging to the current_user with a specified posts.id. In your case for posts/1, current_user.posts.find(params[:id]) would fire SQL query as below

SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = ? AND "posts"."id" = ? LIMIT 1  [["user_id", 1], ["id", 1]]

Make sure that you have a post record with id=1 which belongs to user_id=1.

You are receiving the error, because in your post table, post entry with id=1 does not belong to user_id=1.

Upvotes: 2

Related Questions