2
votes

Done a lot of reading on the situation below. Want some opinions.

In the thread at (1) the user asks "How to create another object when creating a Devise User from their registration form in Rails?". This is exactly what I am trying to do as well. When a user registers I want to create an Account object.

(1) How to create another object when creating a Devise User from their registration form in Rails?

However there's a problem I've been having, which also surfaced at the referenced thread. When I run the following in my subclassed registrations controller. I get "When assigning attributes, you must pass a hash as an argument." ArgumentError in RegistrationsController#create.

class RegistrationsController < Devise::RegistrationsController
    after_action :create_account, only: [:create, :update]


    private
    def create_account
        Account.create(@user)
    end
end

It turns out that using callbacks don't work because I don't have access to the params hash. I've tried so many different variations of the Account.create(current_user) or (@user) as well as adding another def below to try to permit the user id param to go to user_id foreign key of Account. Still the same error "When assigning attributes, you must pass a hash as an argument."

def account_params
    params.require(:account).permit(:user_id,:user)
end

This is where the question at (1) ended up. It proposed bypassing Devise's RegistrationsController.

Is this the only remaining way to achieve the objective of creating other models when a User registers in Devise? Any other suggestions? I don't want to commit to bypassing the registrations controller unless its the only way.

Thanks for any suggestions and happy to provide any other information.

class Account < ApplicationRecord
    has_many :users
end

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :projects
  has_many :notes
  belongs_to :account
1

1 Answers

0
votes

In your user.rb file, you could do this:

after_create :create_account

def create_account
  @user = User.last
  @account = Account.new
  @user.account = @account
  @user.save
  @account.save
end