gpt4 book ai didi

ruby-on-rails - ruby rails : undefined method 'before_save'

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:29 25 4
gpt4 key购买 nike

我正在尝试将多个变量(多项选择测验的整数答案)组合成一个显示结果的字符串(例如“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>

我收到一个 Action Controller 错误,说明 QuizBsController:Class 的未定义方法“before_save”。知道我哪里出错了吗?

bscode 是对“QuizBs”表的补充(来自后来的迁移):

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

关于ruby-on-rails - ruby rails : undefined method 'before_save' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36900495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com