#mint:0x00000004fcac48>的未定义方法`current_user'

时间:2015-12-01 08:28:15

标签: ruby-on-rails

我在我的Rails项目中使用Devise gem。我使用Devise的原因是因为我只想登录用户可以评价他们的老师。现在,我在ratings_controller.rb中收到此错误,尽管我已将user_id添加到我的评级和教师表中。

class RatingsController < ApplicationController
  def new
    get_teacher
    @rating = @teacher.current_user.ratings.build
  end

  def create
    get_teacher
    @rating = @teacher.current_user.ratings.create(rating_params)
    if @rating.save
      redirect_to school_teacher_path(@teacher.school, @teacher)
    else
      render 'new'
    end
  end

  def destroy
    get_teacher
    @rating = @teacher.ratings.find(params[:id])
    @rating.destroy

    redirect_to school_teacher_path(@teacher.school, @teacher)
  end

  def get_teacher
    @teacher = Teacher.find(params[:teacher_id])
  end

  private

    def rating_params
      params.require(:rating).permit(:easiness, :helpfulness, :clarity, :comment,
      :teacher_id, :school_id)
    end
end

这是我的 ratings_controller.rb

class Rating < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :user
end

rating.rb:

class Teacher < ActiveRecord::Base
  belongs_to :school
  has_many :ratings, dependent: :destroy
  has_many :users

  def name
    "#{firstName} #{middleName} #{lastName}"
  end

  def to_s
    name
  end
end

teacher.rb:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :ratings
  has_many :teachers
end

user.rb:

String

3 个答案:

答案 0 :(得分:1)

current_user是控制器助手,它不是模型的实例方法。

您可以在控制器中添加before_action :authenticate_user!以确保只有登录用户可以评分

答案 1 :(得分:1)

您可以在此处更改多个代码。在修复代码之前,我建议您使用before_action来制作DRY代码。

class RatingsController < ApplicationController
  before_action :authenticate_user!
  before_action :get_teacher

  # your code #

  private
    def get_teacher
      @teacher = Teacher.find(params[:teacher_id])
    end

    def rating_params
      params.require(:rating).permit(:easiness, :helpfulness, :clarity, :comment, :teacher_id, :school_id)
    end
end

然后,在before_action :authenticate_user!上方添加before_action :get_teacher,这样您就可以在每种方法中获得current_user

最后,您必须将newcreate方法修复为:

def new
  @rating = current_user.ratings.build
end

def create
  @rating = current_user.ratings.create(rating_params)
  if @rating.save
    redirect_to school_teacher_path(@teacher.school, @teacher)
  else
    render 'new'
  end
end

由于@teacher.current_user.ratings.create(rating_params)中有teacher_id,您无需teacher_id即可获得rating_params。我希望这能帮到你。

答案 2 :(得分:0)

您需要为用户构建评级对象,如下所示: -

@rating = current_user.ratings.build