2015-01-29 4 views
1

Я столкнулся с несколькими вопросами по этой теме, но все они выглядят out of date или просто плохое кодирование.Rails Devise - зарегистрировать пользователя с ассоциированной моделью

Проблема: я подписываю пользователя как часть потока проверки. Я хочу получить адрес пользователя при регистрации. У меня есть модель пользователя и модель адреса. Я не могу понять, как правильно переопределить контроллер регистрации Devise, чтобы разрешить дополнительные параметры.

Вот что я начал с:

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 

Я также получил мой адрес модель:

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

... в routes.rb:

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

И, наконец, моя попытка переопределить контроллер регистрации разработки:

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

В вашем 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 

Теперь в форме регистрации вы можете использовать address_attributes & DEViSE Signup PARAMS примет это.

Теперь, чтобы спасти от цепи фильтра остановленном, пожалуйста, попробуйте это в вашем файле registrations_controller.rb

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

Еще получаю ошибку Самовольная параметры: 'Обработка по завещанию :: RegistrationsController # создать в HTML Параметры: {" utf8 "=>" ✓ "," authenticity_token "=>" dxxx "," user "=> {" email "=>" [email protected] "," password "=>" [FILTERED] "," password_confirmation "= > "[FILTERED]", "first_name" => "absci", "last_name" => "aisbc", "addresses_attributes" => {"0" => {"address" => "asii", "address2" = > «aijsd», «city» => «sdf», «state» => «1», «zip_code» => «22020»}}}, «terms» => «on», «commit» => " Зарегистрироваться "} Непроизведенные параметры: addresses_attributes' –

+0

Собственно, неважно. Я изменил символ из 'address_attributes' на' addresses_attributes', но теперь у меня все еще есть эта ошибка: «Цепочка фильтра остановлена ​​как: require_no_authentication rendered or redirected» и нет 'User.last.addresses' –

+0

для этой ошибки в цепочке фильтров. я обновил свой ответ. добавьте перед аутентификацией before_filter аутентификацию для действия create. – Ajay

Смежные вопросы