开发者

Why is current_user giving me an error?

In my create method in the Videos controller, this line works:

@video = Video.new(params[:video])

However, I want to assign the video to the user, so I use this line which gives me an error:

开发者_如何学运维@video = current_user.videos.new(params[:video])

This is the error:

NoMethodError in VideosController#create

undefined method `videos' for nil:NilClass

I have this in my User model:

has_many :videos

And this in my Video model:

belongs_to :user

This is in my application_controller file:

  def current_user
    return unless session[:user_id]
    @current_user ||= User.find_by_id(session[:user_id]) 
  end

  # Make current_user available in templates as a helper
  helper_method :current_user

How do I fix this error? Let me know if I should post anymore code.


Is this error only happening when the user is not logged or there's no session[:user_id]?

When not logged in:

@video = current_user.videos.new(params[:video])

...would be...

@video = nil.videos.new(params[:video])

which would give you that exact NoMethodError

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜