Reputation: 1437
I am trying to combine several variables (integer answers for a multiple choice quiz) into one string that shows the results (e.g. "614-131").
I have the following in my 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
The string should eventually be displayed in the show.html.erb
page of the users module:
<h4>Body Structure</h4>
<h3><%= @user.bscode %></h3>
I am getting an Action Controller error stating undefined method 'before_save' for QuizBsController:Class
. Any idea where I'm going wrong?
bscode
is an addition (from a later migration) to the 'QuizBs' table:
class AddBscodeToQuizBs < ActiveRecord::Migration
def change
add_column :quiz_bs, :bscode, :string
end
end
QuizBs
is set to belongs_to :user
and a user has_one :quiz_bs
.
Upvotes: 1
Views: 4286
Reputation: 2784
before_save
is to be used in your model.
It is an ActiveRecord Callback, which is triggered when you save your model object.
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
You should be using the following code in you Model
before_save :set_bscode
def set_bscode
self.bscode = "#{self.bs01}#{self.bs02}#{self.bs03}-#{self.bs04}#{self.bs05}#{self.bs06}"
end
Upvotes: 7