每个人必须从表格中 Select 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 %>

我的Carbon 足迹模型:

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
  

我的Carbon 足迹模型

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

当我try 显示结果时,出现以下错误:无法将NIL强制为浮点型

当我看到对象是如何保存到数据库的时候,我看到每个选项都是nil.

推荐答案

在您的select呼叫中,您将选项设置为CarbonFootprint.emission_values[category].keys,这意味着每个选项的名称和值将只是密钥本身,例如.plug_in表格中提交的value个数字不是"fossil_fuel"就是"renewable",而不是实际数字.您应该删除.keys,并发送{ fossil_fuel: 2.5, renewable: 0.5 }的整个散列等等.

Ruby-on-rails相关问答推荐

在ransackable_scopes中的作用域上创建activeadmin过滤器

如何在嵌套路由中使用Ruby on rails多态关联

如何从 gem 覆盖 JSONAPI.configure

Rails 3.1 assets资源 - 奇怪的开发服务

Rails Active Record - 从关系中获取 ids 数组

无法连接 localhost:3000 ruby​​ on rails in vagrant

如何将 Ruby 哈希转换为 XML?

使用 Devise 令牌登录,这是内置的吗?

Heroku 错误 R14(超出内存配额):我该如何解决?

不带参数的 request.fullpath

activerecord 查找所有未包含在数组中的内容

为什么 respond_with 被从 rails 4.2 移除到它自己的 gem 中?

使 rails 控制台输出更漂亮一点

导轨链接到:远程

如何在 Rails 中设置路由的默认格式?

Mongoid OR 查询语法

如何在每个操作的基础上禁用 Ruby on Rails 的日志(log)记录?

使用 heroku 和 namecheap 设置自定义域

使用连接的 Ruby on Rails ActiveRecord 查询

sass-rails 助手image-url、asset-url在 rails 3.2.1 中不起作用