【发布时间】:2020-11-08 06:23:55
【问题描述】:
我正在关注本教程 [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})
我很惊讶地看到 'belonged' 可以有 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/
【问题讨论】:
标签: forms devise nested-attributes ruby-on-rails-6 accepts-nested-attributes