Ben Smith Ben Smith - 5 months ago 13
Ruby Question

Ruby on Rails: How to store data in two tables following the creation of a record in one?

I have two database tables Users and Accounts, when a new user is created their primary email address that they will use to login is stored in the Users table. What I want to do is also store a copy of their primary email address in the Accounts table, as this table will be used to store the email addresses of that user.

I have tried the following in my

users_controller
:

class UsersController < ApplicationController

def index
@users = User.all
end

def show
@user = User.find(params[:id])
end

def new
@user = User.new
end

def edit
@user = User.find(params[:id])
end

def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
@account = Account.new(email: params[:primaryemailaddress], user_id: session[:user_id])
redirect_to @user
else
render 'new'
end
end

def update
@user = User.find(params[:id])

if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end

def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to users_path
end

private

def user_params
params.require(:user).permit(:title, :firstname, :surname, :housenumber, :street, :city, :postcode, :organisation, :primaryemailaddress, :password)
end
end


And the following in my
User
model:

class User < ActiveRecord::Base
has_many :accounts
accepts_nested_attributes_for :accounts
validates :primaryemailaddress, presence: true
has_secure_password
end


So, as you can see in the
create
method in the
users_controller
, I am trying to create a new record in the Accounts table using the primary email address the user has entered on the registration form.

Can someone please tell me where I am going wrong?

Answer

Please try with below modification

  def create
    @user = User.new(user_params)
    if @user.save       
      session[:user_id] = @user.id
      @account = Account.create(email: params[:user][:primaryemailaddress], user_id: session[:user_id])
      redirect_to @user
    else
      render 'new'
    end
  end