RoR - NoMethodError,未定义的方法

时间:2015-04-21 09:48:49

标签: ruby-on-rails ruby methods

我创建了一个简单登录身份验证的应用程序,它实际上是一个Twitter克隆。用户登录并访问页面等

但是,当用户从该个人资料中发布内容时。它给出了一个错误

NoMethodError in RibbitsController#create
undefined method `id=' for nil:NilClass

错误在第5行附近:

class RibbitsController < ApplicationController

 def create
   @ribbit = Ribbit.create(user_ribbits)
   @ribbit.userid = current_user.id

   if @ribbit.save
       redirect_to current_user 
   else
       flash[:error] = "Problem!"
       redirect_to current_user
   end
 end

 private

 def user_ribbits
      params.require(:ribbit).permit(:content, :userid)
    end
end

给app的请求:

Request

参数:

{"utf8"=>"✓",
 "authenticity_token"=>"dwVmjDNO4GOowphGFgChMDBxBfvka+M/xSUHvJMECzwxtv4NF6OuWtiaX74NLz91OwQJ9T9+wm7yMiPQ0BLpGA==",
 "ribbit"=>{"content"=>"hi. test.\r\n"},
 "commit"=>"Ribbit!"}

会话控制器:

class SessionsController < ApplicationController

  def new
  end

  def create
   user = User.find_by_username(params[:username])
    if user && user.authenticate(params[:password])
        session[:userid] = user.id
        redirect_to rooturl, notice: "Logged in!"
    else
        flash[:error] = "Wrong Username or Password."
        redirect_to root_url
    end
  end

  def destroy
   session[:userid] = nil
    redirect_to root_url, notice: "Logged out."
  end

end

用户控制器:

class UsersController < ApplicationController

 def new
     @user = User.new
 end

 def create
   @user = User.create(user_params)

   if @user.save
    session[:user_id] = @user.id
     redirect_to @user, notice: "Thank you for signing up!"
   else
     render 'new'
   end
 end

 def show
   @user = User.find(params[:id])
   @ribbit = Ribbit.new
 end

 private

 def user_params
      params.require(:user).permit(:name, :username, :email, :password, :password_confirmation, :avatar_url)
    end

end

和应用程序控制器

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  private

 def current_user
   @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user
end

如果你们有人帮忙我真的很感激!

感谢。

1 个答案:

答案 0 :(得分:1)

您尝试将current_user.id分配给@ribbit.userid,而不确保current_user已设置。只有先前保存过用户才会设置'current_user'。

因此,您需要确保经过身份验证的用户尝试创建Ribbit,或者如果您将userid视为非必填字段,则只需更改第5行即可:

@ribbit.userid = current_user.id unless current_user.blank?

如果您只想让经过身份验证的用户创建Ribbits,请考虑使用gem来处理Devise等身份验证。然后,您可以在控制器中使用before_filter :authenticate_user!以确保用户经过适当的身份验证。