Ruby 在 Rails 上:未定义的方法 'before_save'

Ruby on Rails: undefined method 'before_save'

我正在尝试将多个变量(多项选择测验的整数答案)组合成一个显示结果的字符串(例如“614-131”)。

我的 QuizBsController 中有以下内容:

class QuizBsController < ApplicationController
  before_action :require_sign_in
  before_save :set_bscode

  def set_bscode
    self.bscode = "#{bs01}#{bs02}#{bs03}-#{bs04}#{bs05}#{bs06}"
  end

  def show
    @quiz_bs = QuizBs.find(params[:id])
  end

  def new
    @quiz_bs = QuizBs.new
  end

  def create
    @quiz_bs = QuizBs.new

    @quiz_bs.bs01 = params[:quiz_bs][:bs01]
    @quiz_bs.bs02 = params[:quiz_bs][:bs02]
    @quiz_bs.bs03 = params[:quiz_bs][:bs03]
    @quiz_bs.bs04 = params[:quiz_bs][:bs04]
    @quiz_bs.bs05 = params[:quiz_bs][:bs05]
    @quiz_bs.bs06 = params[:quiz_bs][:bs06]

    @quiz_bs.user = current_user

    if @quiz_bs.save
      flash[:notice] = "Quiz results saved successfully."
      redirect_to user_path(current_user)
    else
      flash[:alert] = "Sorry, your quiz results failed to save."
      redirect_to welcome_index_path
    end
  end

  def update
    @quiz_bs = QuizBs.find(params[:quiz_bs])

    @quiz_bs.assign_attributes(quiz_bs_params)

    if @quiz_bs.save
      flash[:notice] = "Post was updated successfully."
      redirect_to user_path(current_user)
    else
      flash.now[:alert] = "There was an error saving the post. Please try again."
      redirect_to welcome_index_path
    end
  end

  private
  def quiz_bs_params
    params.require(:quiz_bs).permit(:bs01, :bs02, :bs03, :bs04, :bs05, :bs06)
  end

end

该字符串最终应显示在用户模块的 show.html.erb 页面中:

  <h4>Body Structure</h4>
  <h3><%= @user.bscode %></h3>

我收到一个动作控制器错误,说明 undefined method 'before_save' for QuizBsController:Class。知道我哪里出错了吗?

bscode 是对 'QuizBs' table:

的补充(来自后来的迁移)
class AddBscodeToQuizBs < ActiveRecord::Migration
  def change
    add_column :quiz_bs, :bscode, :string
  end
end

QuizBs 设置为 belongs_to :user 并且用户 has_one :quiz_bs.

before_save 将在您的模型中使用。

它是一个 ActiveRecord 回调,在您保存模型对象时触发。

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

您应该在模型中使用以下代码

before_save :set_bscode

def set_bscode
  self.bscode = "#{self.bs01}#{self.bs02}#{self.bs03}-#{self.bs04}#{self.bs05}#{self.bs06}"
end