Techioz Blog

Ruby on Rails 7 を使用して二酸化炭素排出量計算ツールを作成しようとしましたが、ユーザーのオブジェクトを保存できません

概要

値を計算するには、各人がフォームから 4 つのオプションを選択する必要があります。形式は次のとおりです。

<%= form_with(model: @carbon_footprint, local: true) do |form| %>
  <% CarbonFootprint::CATEGORIES.each do |category| %>
    <div class="field">
      <%= form.label category %>
      <%= form.select category, CarbonFootprint.emission_values[category].keys %>
    </div>
  <% end %>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

私の二酸化炭素排出量モデル:

class CarbonFootprintsController < ApplicationController

  def new
    @carbon_footprint = CarbonFootprint.new
  end
  
  def create
    @carbon_footprint = CarbonFootprint.new(carbon_footprint_params)
    @carbon_footprint.user = current_user
    if @carbon_footprint.save
      redirect_to @carbon_footprint, notice: 'Carbon footprint was successfully created.'
    else
      render :new, status: :unprocessable_entity
    end
  end

    private
  
    def carbon_footprint_params
      params.require(:carbon_footprint).permit(:plug_in, :get_around, :consume, :stay_warm_or_cool)
    end

end
  

私の二酸化炭素排出量モデル

class CarbonFootprint < ApplicationRecord
    belongs_to :user 
    validates :user_id, uniqueness: true

    CATEGORIES = [:plug_in, :get_around, :consume, :stay_warm_or_cool]

    def self.emission_values
        {
            plug_in: { fossil_fuel: 2.5, renewable: 0.5 },
            get_around: { fossil_fuel: 2.5, renewable: 0.5 },
            consume: { a_lot: 2.5, a_little: 0.5 },
            stay_warm_or_cool: { fossil_fuel: 2.5, renewable: 0.5 }
        }
    end


    def total
        total = 0.0
        self.class.emission_values.each do |category, options|
          total += options[self[category]]
        end
        total
      end
end

そして私のテーブル

  create_table "carbon_footprints", force: :cascade do |t|
    t.float "plug_in"
    t.float "get_around"
    t.float "consume"
    t.float "stay_warm_or_cool"
    t.bigint "user_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_carbon_footprints_on_user_id"
  end

結果を表示しようとすると、次のエラーが発生します: nil を Float に強制することはできません

そして、オブジェクトがデータベースにどのように保存されるかを確認すると、すべてのオプションで nil が表示されます。

解決策

ビューの選択呼び出しでは、オプションを CarbonFootprint.emission_values[category].keys に設定しています。これは、各オプションの名前と値がキーそのものになることを意味します。 plug_in のフォームに送信される値は、実際の数値ではなく、「fossil_fuel」または「renewable」のいずれかになります。 .keys を削除し、{ fossil_fuel: 2.5, renewable: 0.5 } などのハッシュ全体を送信する必要があります。