Rails Devise-向关联模型注册用户 [英] Rails Devise - Register User with Associated Model
问题描述
我在此主题上遇到了一些SO问题,但似乎都过时了或仅仅是不好的编码习惯。
I've come across a few SO questions on this topic, but all seem out of date or simply bad coding practice.
问题:我正在向用户注册,这是结帐流程的一部分。我想在用户注册时收集用户的地址。我有一个用户模型和一个地址模型。我似乎无法弄清楚如何正确地覆盖Devise的注册控制器以允许其他参数。
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.
这就是我开始的目的:
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中:
...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
推荐答案
在您的application_controller.rb中
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
现在,您可以在注册表格中使用address_attributes&设计注册参数将接受这一点。
Now in your registration form you can use address_attributes & devise signup params will accept this.
现在要停止从过滤器链中恢复,请在您的 registrations_controller.rb
文件中尝试此操作
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
这篇关于Rails Devise-向关联模型注册用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!