Rails Devise - Register User with Associated Model

2019-02-26 02:31发布

问题:

I've come across a few SO questions on this topic, but all seem out of date or simply bad coding practice.

Problem: I am signing up a user as part of a checkout flow. I want to collect the user's address when they sign up. I have a user model and an address model. I can't seem to figure out how to properly override Devise's registration's controller to allow the additional params.

Here's what I've started with:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :orders
  has_many :addresses, :dependent => :destroy

  accepts_nested_attributes_for :addresses

end

I've also got my address model:

class Address < ActiveRecord::Base
  belongs_to :state
  belongs_to :user
end

...in routes.rb:

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

And finally, my attempt at overriding the devise registration's controller:

class RegistrationsController < Devise::RegistrationsController

  before_filter :configure_permitted_parameters

  # GET /users/sign_up
  def new

    # Override Devise default behaviour and create a profile as well
    build_resource({})
    resource.build_address
    respond_with self.resource
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u|
      u.permit(:email, :password, :password_confirmation, :address_attributes => [:address, :address2, :city, :state_id, :zip_code])
    }
  end
end

回答1:

In your application_controller.rb

class ApplicationController < ActionController::Base
before_action :configure_strong_params, if: :devise_controller?

  def configure_strong_params
  devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :name, 
    :addresses_attributes => [:address, :address2, :city, :state_id, :zip_code]) }
  end
end

Now in your registration form you can use address_attributes & devise signup params will accept this.

Now to rescue from the filter chain halted, please try this in your registrations_controller.rb file

class RegistrationsController < Devise::RegistrationsController
 skip_before_filter :require_no_authentication, only: :create
 #other codes 
end