无法将公司(来自单独的模型)添加到设计用户



首次发布海报,网站上的许多时间探索者(谢谢!(。我使用的是Rails 5.2.3,Ruby-2.6.2,并设计GEM 4.6.2。即使这里,这里和这里有很多相关的问题,我也无法得到工作的答案。

当新用户签名时,我希望他们从注册表单中的下拉列表(已经创建(中选择他们的公司。(最终,这将是管理员的角色,但这超出了这个问题的范围。(

我根据以前的许多帖子创建了一个注册控制器和添加的代码。更新,我并没有像本文所示的那样扩展设计:扩展设计注册控制器。这是我的新注册控制器。

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]

  def new
     @companies = Company.all
     super
  end
  def create
    @companies = Company.all
    super
  end
  protected

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

  def configure_account_update_params
     devise_parameter_sanitizer.permit(:account_update, keys: [:company_id])
  end
end

并使用new.html.erb和edit.html.erb在视图/注册中创建了新文件,我从设计/注册视图中复制了确切的代码。

我更新了我的路由。rb文件以包括:

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

我的用户模型是:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  belongs_to :company
  accepts_nested_attributes_for :company
end

我的公司模型是:

class Company < ApplicationRecord
    has_many :users
end

在新的用户注册表格中,这可以提供下拉列表,但是当我尝试创建新用户时,它说:1错误禁止该用户被保存:公司必须存在。

    <%= f.collection_select :company, @companies, :id, :name, prompt: true %>

我以为这篇文章会有答案,但是似乎使用了Rails 3和Attr_Access,该帖子在Rails 4中被弃用4。

我不太了解accept_nested_attributes_for :company的作用。公司模型中唯一的东西是名称。

预先感谢您!

欢迎来到stackoverflow。

为了添加更多参数以设计的注册表单,您需要使用Devise的消毒器对相应的参数进行消毒。

您应该这样做:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?
  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:company_id])
  end
end

您可以在Deaise的Readme

的这一部分中找到有关参数清理和添加自定义字段的更多信息

如果您还想添加一个选择字段,包括所有现有公司,则应添加一个集合:

<%= f.collection_select :company_id, Company.all, :id, :name %>

得到它!

要扩展设计控制器,请在此处遵循帮助:扩展设计注册控制器

还必须更新用户模型以包括可选的:true,因为此处https://blog.bigbinary.com/2016/02/15/rails-5-makes-5-makes-belong-belong-to-association-required-required-by-by-by-default.html:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  belongs_to :company, optional: true
  accepts_nested_attributes_for :company
end

最新更新