###前提・実現したいこと
ruby(rails)で、銀行みたいなアプリをつくっています。
銀行のように一人の顧客が一つだけ口座を開設できるのと同じように・・・
ユーザーが新規会員登録したと同時に、
ユーザーモデルと1:1の関係にあるアカウントモデルに
レコードを自動作成をしたいのですが、よくわからず困っています。
もう少し具体的に言うとこんな感じです。
ユーザーがdeviseでメールアドレスとパスワードを入力して会員登録を済ませます。
そして会員登録が成功したとき、自動的にアカウントが作成されます。
このとき、ユーザーは何も入力せずにアカウントテーブルに、
「user_id(ユーザーと紐づく為の外部キー)」
「アカウント番号(他のアカウント番号と被らないランダムな11桁の番号)」
「残高(デフォルトで0.00)」
という内容がつくられるようにしたいと考えています。
この場合、どんな実装をすればいいのか教えて頂ければ幸いです。
###試しに書いたソースコード
model部分だけ書いてみました。
class User < ApplicationRecord has_one :account before_create :build_default_account # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable private def build_default_account build_account true end end
class Account < ApplicationRecord belongs_to :user validates :user_id, presence:true def load_defaults #もしDBに保存されていない(新規登録)ならば、口座番号をランダムに作成する #もしDBに保存されていない(新規登録)ならば、残高を0にする。 if self.new_record? self.account_number = SecurRandom.uuid self.balance = 0.00 end end end
###補足情報(言語/FW/ツール等のバージョンなど)
Rails 5.1.3
ruby 2.4.1
devise (4.3.0)
###アドバイスを参考に変更したファイル内容を追記(成功)
以下には、アドバイスを参考にコードを修正し、最終的に成功したコード内容を追記しておきます。
model.user.rbを編集。
class User < ApplicationRecord has_one :account # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end
model/account.rbを編集。
class Account < ApplicationRecord belongs_to :user end
app/controllersにhoges_controller.rbを作成して編集。
class HogesController < ApplicationController def index @account = Account.all end def new @user = User.new end def create @user = User.new(user_params) @user.build_account #Userの子要素であるアカウントを関連付ける # インカムアカウントテーブルのaccount_numberのカラムに代入する @user.account.account_number = SecureRandom.random_number(1000000000000) @user.account.balance = 0 @user.save redirect_to '/hoges/index' end private def user_params params.require(:user).permit(:password, :email) end def account_params params.require(:account).permit(:account_number, :balance) end end
/app/views/hogeにindex.html.erbを作成して編集。
<p>index.html.erb</p> <p>作成画面</p> <%= form_for(@user) do |f| %> <div class= "field"> <%= f.label :email %> <%= f.email_field :email %> <%= f.label :password %> <%= f.password_field :password %> <%= f.submit "会員登録" %> <% end %> </div>
routes.rbに追記する。
Rails.Application.routes.draw do ・・・ get 'hoges/index' get 'hoges/new' post 'users' => 'hoges#create' ・・・ end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。