Current_user不返回值

时间:2014-03-10 18:47:39

标签: ruby-on-rails null

我的current_user函数在我的Post控制器中不起作用。 当我尝试显示/ posts / 1时,这是dbconsole中的第一条记录,我发现了这个错误:

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

查看我的来源:发布模型:

class Post < ActiveRecord::Base
    belongs_to :user
end

发布模型:

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

应用程序控制器:

  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

问题仅出现在后期控制器中:

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

可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

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

以上内容将查找属于current_user且具有指定posts.id的帖子。对于posts/1的情况,current_user.posts.find(params[:id])会触发SQL query,如下所示

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

确保您的id=1帖子属于user_id=1

您收到错误,因为在您的帖子表中,id = 1的帖子条目不属于user_id = 1.