私の最初の Rails プロジェクトでは、SimpleForm gem を使用してフォームを作成しようとしています。フォームにはラジオ ボタン形式の質問があり、各回答にはスコア (1 ~ 4) が関連付けられています。私の目的は、フォームに各質問 (:vision_problems、:balance_issues、:nausea) のスコアを合計し、ユーザーがフォームを送信すると、合計スコアを別の列 (:total) に保存することです。この問題にアプローチする最善の方法は何ですか?
現在、以下を使用して Show ビューに合計を表示していますが、:total 列がある方がはるかに優れています。
<%= @total = @symptom.nausea + @symptom.balance_issues + @symptom.vision_problems %>
助けてくれてありがとう。
ビューのフォーム部分:
<%= simple_form_for(@symptom) do |f| %>
<%= f.error_notification %>
<%= f.input :vision_problems, label_html: { class: "buttonhead" }, collection: [ 1 , 2, 3,
4 ], as: :radio_buttons %>
<%= f.input :balance_issues, label_html: { class: "buttonhead" }, collection: [ 1 , 2, 3,
4 ], as: :radio_buttons %>
<%= f.input :nausea, label_html: { class: "label label-info" }, collection: [ 1 , 2, 3,
4 ], as: :radio_buttons %>
<%= f.button :submit, class: "btn btn-primary" %>
<% end %>
症状モデル:
class Symptom < ActiveRecord::Base
attr_accessible :description, :vision_problems, :balance_issues, :nausea, :user_id, :total
belongs_to :user
validates :user_id, presence: true
end
症状コントローラーの作成部分:
def create
@symptom = current_user.Symptoms.new(params[:symptom])
respond_to do |format|
if @symptom.save
format.html { redirect_to @symptom, notice: 'Symptom was successfully created.' }
format.json { render json: @symptom, status: :created, location: @symptom }
else
format.html { render action: "new" }
format.json { render json: @symptom.errors, status: :unprocessable_entity }
end
end
end