Rails5.1.3でWebアプリケーション制作の勉強をしています。CustomersテーブルとPointsテーブルがあるのですが
Pointsテーブルに入力フォームで入力したデータを保存する際に外部キー(customer_id)の値も入れたいのですが
どこにどのように記述したらいいのでしょうか?コードは以下になります。
points_controller.rb def create @point_form = Customer::PointForm.new @point_form.assign_attributes(params[:form]) if @point_form.save flash.notice = 'ポイントを登録しました。' redirect_to action: 'show' else flash.now.alert = '入力に誤りがあります。' render actionn: 'new' end end
point.rb (モデル) class Point < ActiveRecord::Base belongs_to :customer end
new.html.erb <% @title = 'ポイントの新規登録' %> <h1><%= @title %></h1> <div id="generic-form"> <%= form_for @point_form, as: 'form', url: :customer_point do |f| %> <%= render 'form', f: f %> <div class="buttons"> <%= f.submit '登録' %> <%= link_to 'キャンセル', :customer_root %> </div> <% end %> </div>
_form.html.erb <%= FormPresenter.new(f, self).notes %> <fieldset id="Point-fields"> <legend>ポイント情報(正確に入力してください。)</legend> <%= render 'point_fields', f: f, confirming: false %> </fieldset>
_point_fields.html.erb <%= f.fields_for :point, f.object.point do |ff| %> <%= markup do |m| p = confirming ? ConfirmingPointFormPresenter.new(ff, self) : PointFormPresenter.new(ff, self) p.with_options(required: true) do |q| m << q.1game_block(:1game, '1回目') m << q.2game_block(:2game, '2回目') m << q.3game_block(:3game, '3回目') m << q.4game_block(:4game, '4回目') m << q.5game_block(:5game, '5回目') end end %> <% end %>
createアクションに以下のように記述したらいいのでしょうか?
points_controller.rb def create @point_form = Customer::PointForm.new @point_form.assign_attributes(params[:form]) #①のコード customer = Customer.find_by(id: current_customer.id) point = customer.build_point(customer_id: current_customer.id) point.save #②のコード customer = Customer.find_by(id: current_customer.id) customer.point.update(customer_id: current_customer.id) if @point_form.save flash.notice = 'ポイントを登録しました。' redirect_to action: 'show' else flash.now.alert = '入力に誤りがあります。' render actionn: 'new' end end
①のコード、②のコードのどちらかのような感じでいいのでしょうか?
それとも別のコード(方法)があるのでしょうか?
どなたか教えていただけないでしょうか?宜しくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/18 10:56