Paul Harker
Paul Harker

Reputation: 166

Overriding Devise Parameters

I'm building an application that takes an admin and a company in one form and connects the two. The connection part is setup with a belongs_to relationship (Admin belongs to the company).

The problem I have is that I'm using Devise and it automatically takes all my params and tries to make a user. The thing is, in the params, the company is just a name string. So I need to build the company, then send (presumably) the company_id to Devise, or set it up myself afterwards.

This is what I've tried in the Admin:RegistrationController.

def create
  @company = Company.create(name: params[:admin][:company])
  super
  @admin.company = @company
end

This fails to create the Admin, and Devise returns the error "The Company must exist". And is also obviously rather hacky (or at least feels that way).

What should I do here, and what is the best practice? Thanks!

Upvotes: 0

Views: 510

Answers (2)

widjajayd
widjajayd

Reputation: 6253

create override one new file in folder app/controllers/admins/registration_controller.rb and add this command below (some part is devise standard command)

class Admins::RegistrationsController < Devise::RegistrationsController

  def create
    build_resource(sign_up_params)
    @company = Company.create(name: params[:admin][:company])
    # resource is standard
    resource.company   = @company
    resource.save
  end

end

Upvotes: 0

max
max

Reputation: 102046

You can override #build_resource to hook into the original #create implementation:

class Admin:RegistrationController < ::Devise::RegistrationsController
  def build_resource(hash = {})
    super
    if action_name == "create"
      self.resource.company ||= Company.create 
    end
  end
end

However from a UX perspective it might be a better idea to let the user select existing companies through a select or use accepts_nested_attributes to let the user fill in fields for the company.

You could also make the association optional and let the user fill in the company details after registration.

what is the best practice?

Whatever way accomplishes the requirements on time.

Upvotes: 1

Related Questions