Search code examples
ruby-on-railsdeviseslim-lang

Devise, create a user that belongs to company


I want to create a user with Devise, that have a belongs_to association.

What is missing? What needs to create a user that belongs to a company from a select list?

my form have this:

.siimple-form-field
        = f.label :name, class: "siimple-label"
        br
        = f.text_field :name, autofocus: true, autocomplete: "email", class: "siimple-input siimple-input--fluid siimple--height-50"
      .siimple-form-field
        label.siimple-label
          | Select an option:
        = f.fields_for :company_attributes do |b|
          = b.select :company, Company.all.collect{|p| [p.name, p]}, {}, class: "siimple-select siimple-select--fluid"

the form shows ok, so when i try to submit, it says:

1 error prohibited this user from being saved:

    Company must exist

Also my RegistrationsController have:

def create
  super
end


def configure_sign_up_params
  devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :bank])
end

Solution

  • Solved!

    First them all, the registration controller was not overriden in the routes files, just got this:

    devise_for :users, controllers: {
        sessions: 'users/sessions',
        # something missing no?
    
      }
    

    Fixed it with

    devise_for :users, controllers: {
        sessions: 'users/sessions',
        registrations: 'users/registrations'
    
      }
    

    Then, just do common things like add something like this to the controller:

    def create
      params[:user][:company] = Company.find(params[:user][:company_id])
      super
    end
    

    And add the missing permission to configure_sign_up_params

    def configure_sign_up_params
      devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :company_id, :company])
    end