1

我正在关注本教程 [https://kakimotonline.com/2014/03/30/extending-devise-registrations-controller/][1],其目的是在同一表格上创建一个设计用户及其所属公司。

楷模 :

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable

  belongs_to :company, optional: true
  accepts_nested_attributes_for :company

end
user model has a reerence to company :
add_reference(:users, :company, {:foreign_key=>true})

我很惊讶地看到“属于”可以有 accept_nested 提及(以为只有所有者可以)

class Company < ActiveRecord::Base
 
  has_one :user
 
end

表单视图是:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <div class="controls">
    <%= f.fields_for :company do |company_form| %>
      <%= company_form.text_field :cnpj  %>
    <% end %>
  </div>
  <div class="controls">
    <%= f.text_field :email %>
  </div>
  <div class="controls">
    <%= f.password_field :password %>
  </div>
  <div class="controls">
    <%= f.password_field :password_confirmation %>
  </div>
  <%= f.submit "Submit" %>
<% end %>

创建注册控制器以替换默认控制器:

**controllers/registrations_controller.rb**
class RegistrationsController < Devise::RegistrationsController
 
  def new
    build_resource({})
    self.resource.company = Company.new
    respond_with self.resource
  end
  
  def create
    @user = User.new sign_up_params
    @user.save
  end
end

strong_prams 权限:

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

  protected

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

这条路线

MyApp::Application.routes.draw do
 
  devise_for :users, controllers: { registrations: "registrations" }
 
end

在控制台上,我可以创建实例:

User.create(email:'test@gmail.com',
            password:'password',
            password_confirmation:'password',
            company_attributes: { name: 'nours' })

创建一个用户和他的关联公司:)

但是表单在 #create : 中失败。路线有效,参数正常,#create 检索正确的允许值,

=>{"email"=>"tota@gmal.com", "password"=>"zigzig", "password_confirmation"=>"zigzig", "company_attributes"=>{"name"=>"tata toto"}}```
but creation of instance 
```>> User.new(sign_up_params) 
=> #<User id: nil, email: "", created_at: nil, updated_at: nil, company_id: nil>```, 
the same with 
```>> build_resource sign_up_params  
=> #<User id: nil, email: "", created_at: nil, updated_at: nil, company_id: nil>```

What's wrong with strong_params ?


  [1]: https://kakimotonline.com/2014/03/30/extending-devise-registrations-controller/
4

1 回答 1

1

您收到此错误的原因是因为您belongs_to :company在用户模型中。这意味着必须有一家公司,否则用户将无法保存。尝试将其更改为belongs_to :company, optional: true.

从 Rails 5.0 开始,“所有模型的belongs_to关联现在都被视为required: true存在选项”。您可以在此处了解更多信息。

于 2020-07-18T21:00:25.773 回答