我试图将几个变量(多项选择测验的整数答案)组合成一个显示结果的字符串(例如“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'表:
class AddBscodeToQuizBs < ActiveRecord::Migration
def change
add_column :quiz_bs, :bscode, :string
end
end
QuizBs
设置为belongs_to :user
,用户设置为has_one :quiz_bs
。
答案 0 :(得分:6)
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