LoginSignup
27
33

More than 5 years have passed since last update.

[Rails]フォームで入力した値を計算して別の値をデータベースに入れる

Posted at

やりたいこと

  • 身長体重カラムを持ったモデルがあるとする
  • フォームで身長体重を送信すると同時にBMI,身長を2倍したものをデータベースに格納

要は身長体重を入力させるだけでその他の情報もデータベースに格納したいとき

私の回答

persons/new.html.erb
...
<%= form_for(@person) do |f| =%>
  <%= f.text_field :weight =%>
  <%= f.text_field :height =%>
<% end %>
...
person.rb
class Person < Application
  def bmi
    weight / height ** 2
  end

  def height_2
    height * 2
  end

  def set_extra_information
  {:bmi => bmi, :height_2 => height_2 }
  end
end
persons_controller.rb
def new
  @person = Person.new
end

def create
  @person = Person.new(person_information)
  @person.save
end

private

def person_params
  params.require(:person).permit(:height, :weight)
end

def person_information
  person_params.merge(@person.set_extra_information)
end

入力されたフォームをperson_paramsで受け取ってそれをそのままインスタンス生成するのではなくてperson_informationというメソッドでhashとしてマージすることでデータベースにBMI,身長を2倍したものを格納できる

正しいのかわからないにゃあ

27
33
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
33