[英]Rails: How do I make a calculation using form input variables in the create action of a controller before saving it in the db?
在我的表格中,用戶輸入他/她的體重和體脂百分比。 在我的控制器create action中,我想計算人的瘦體重並將其保存到數據庫的lean_mass列中。
lean_mass = weight * (1 - body_fat)
schema.rb
create_table "stats", force: true do |t|
t.integer "user_id"
t.integer "weight"
t.decimal "body_fat"
t.integer "lean_mass"
t.date "date"
t.datetime "created_at"
t.datetime "updated_at"
end
統計/ new.html.erb
<%= form_for @stat do |f| %>
<%= f.label :date %>
<%= f.date_field :date %>
<%= f.label :weight %>
<%= f.number_field :weight %>
<%= f.label :body_fat %>
<%= f.number_field :body_fat, step: 0.1 %>
<%= f.submit %>
<% end %>
stats_controller.rb
class StatsController < ApplicationController
before_action :authenticate_user! #I'm using devise
def index
@stats = current_user.stats
end
def new
@stat = current_user.stats.build
end
def create
##
###How do I calculate and add lean_mass to stat_params here?###
##
@stat = current_user.stats.build(stat_params)
if @stat.save
redirect_to root_url, notice: "Stat was successfully created."
else
redirect_to dashboard_url, notice: "Problem creating stat."
end
end
private
def stat_params
params.require(:stat).permit(:date, :weight, :body_fat)
end
end
我需要有關create操作的幫助。
您將必須首先計算稀薄質量:
lean_mass = params[:stat][:weight].to_i * (1 - params[:stat][:body_fat].to_i)
然后可以將其添加到新的@stat
對象中
@stat = current_user.stats.build(stat_params.merge(:lean_mass => lean_mass))
# OR
@stat.lean_mass = lean_mass
然后,您可以繼續並保存對象。
假設您像這樣驗證weight
和body_fat
列的存在:
stat.rb
validates_presense_of :weight, :body_fat
由於lean mass
始終取決於weight
和weight
, body_fat
我建議兩件事:
1)您可以在模型中添加方法 lean_mass
來返回計算出的值,因此不再需要該列。
stat.rb
def lean_mass
self.weight * (1 - self.body_fat)
end
2)添加一個after_save
回調 ,該回調自動計算並存儲lean_mass
值
stat.rb
after_save { self.update(:lean_mass => self.weight * (1 - self.body_fat)) }
強烈建議使用這些解決方案之一,因為您不必擔心create
或update
操作中的lean mass
列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.