gpt4 book ai didi

ruby-on-rails - 如何以单个嵌套形式实现 Rails 4 Devise 用户注册公司名称

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:45 25 4
gpt4 key购买 nike

我有一个 Rails 4 应用程序,它有一个简单的默认 Devise 注册流程和一个用户模型。现在,我添加了一个公司模型,公司模型与用户模型之间存在一对多关系(公司有_许多用户,用户属于公司)。

我希望用户在注册时选择公司名称,因此注册表单有 3 个字段:公司名称、用户电子邮件和密码。

我收到“Unpermitted parameters: company”错误,尽管我认为我正在处理强参数问题。

我已经阅读了类似问题的所有 SO 答案,但没有一个答案有效。我的代码的相关片段如下:

#routes.rb
devise_for :users, :controllers => { :invitations => 'users/invitations',
:registrations => 'users/registrations',
:omniauth_callbacks => "users/omniauth_callbacks"
}

resources :companies


#MODELS
#user.rb
class User < ActiveRecord::Base
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable, :omniauth_providers => [:google_oauth2, :mailchimp, :stripe_connect, :xero]

belongs_to :company
accepts_nested_attributes_for :company
end

#company.rb
class Company < ActiveRecord::Base
has_many :users
end



#CONTROLLER
#users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters

def new
build_resource({})
self.resource.company = Company.new
respond_with self.resource
end

def create
super
end

protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation, company_attributes: [:name])
end
end
end


#application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery

def after_sign_in_path_for(resource)
#some_path
end
end



#VIEW
#sign up form
= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
= devise_error_messages!
.form-group
= f.email_field :email, placeholder: "Email", class: "form-control"
= hidden_field_tag "plan", params[:plan]
.form-group
= f.password_field :password, placeholder: "Password", class: "form-control"
.form-group
= f.fields_for resource.company do |cf|
= cf.text_field :name, placeholder: "Name of your company", class: "form-control"
.submit= submit_tag "Sign up now", :class => "button"

传递给 Users::RegistrationsController 的参数散列如下:

{"utf8"=>"✓", "authenticity_token"=>"uWMrX3qVTLL2A1g1ONtBxuj72/GMRZqG5rcOvba/8p4=", "user"=>{"email"=>"x@foo.com", "password"=>"password", "company"=>{"name"=>"F corp"}}, "plan"=>"x", "commit"=>"Sign up now"}

最佳答案

您的 params sanitizer 似乎不太正确。试试这个:

def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation, company: [:name])
end
end

参见 Nested Parameters有关详细信息,请参阅强参数文档部分。

关于ruby-on-rails - 如何以单个嵌套形式实现 Rails 4 Devise 用户注册公司名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com