我正在使用Rails 5.2.2。我正在尝试通过devise使用嵌套属性。我创建了关联,迁移和视图。
这是我的路线。rb:
Rails.application.routes.draw do
devise_for :users
resources :companies, :has_many => :users
get 'welcome/index'
root "welcome#index"
end
User.rb:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
belongs_to :company
accepts_nested_attributes_for :company
end
Company.rb:
class Company < ApplicationRecord
has_many :users
end
我的自定义设计参数引起关注:
module DevisePermitter
extend ActiveSupport::Concern
included do
before_action :permitted_devise_parameters, if: :devise_controller?
end
def permitted_devise_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name,:gsm,:role,:company_id,company_attributes:[:name,:tax_no,:city]])
devise_parameter_sanitizer.permit(:account_update, keys: [:name,:gsm,:id_no,:profile_picture,:socials])
end
end
当我单击提交按钮时,它将返回相同的sign_up页面,而不记录值。这是服务器响应:
Started GET "/users/sign_up?utf8_SHORTENED-HERE" for 127.0.0.1 at 2018-12-26 10:32:51 +0300
Processing by Devise::RegistrationsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"yBS9+sMyfSq0BYAd5LuodZCuJ9vHLFaxohrZjbOCdmv1m4SYUVI4XpE2GKmeY1eM0GhHEgtcnBZK7I8c0PuAHA==", "user"=>{"email"=>"asd@yandex.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "company_attributes"=>{"name"=>"asd asd", "tax_no"=>"42123", "city"=>"asda"}, "name"=>"sadaf", "gsm"=>"1231313", "role"=>"asdas"}, "commit"=>"Register"}
Rendering devise/registrations/new.html.erb within layouts/devise1
Rendered devise/registrations/new.html.erb within layouts/devise1 (3.4ms)
Completed 200 OK in 19ms (Views: 17.7ms | ActiveRecord: 0.0ms)
当我尝试使用Rails控制台保存数据时,它会起作用:
User.create!({"email"=>"asd@yandex.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "company_attributes"=>{"name"=>"asdasd", "tax_no"=>"asdasd", "city"=>"asdasd"}, "name"=>"asdasd asd", "gsm"=>"313121", "role"=>"asdasd"})
我正在传递某些东西,但是我找不到它。
答案 0 :(得分:0)
在/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :permitted_devise_parameters, if: :devise_controller?
protected
def permitted_devise_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name,:gsm,:role,:company_id,company_attributes:[:name,:tax_no,:city]])
devise_parameter_sanitizer.permit(:account_update, keys: [:name,:gsm,:id_no,:profile_picture,:socials])
end
end
并注释掉DevisePermitter
中的代码,看看会发生什么
答案 1 :(得分:0)
我发现了问题。问题出在我看来,form_for标记未在表单元素中生成action =“ \ users”和method =“ post”。
通过创建有效的form_for标签来解决。
答案 2 :(得分:0)
从allowed_devise_parameters方法中删除company_id。
def permitted_devise_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name,:gsm,:role, company_attributes:[:name,:tax_no,:city]])
devise_parameter_sanitizer.permit(:account_update, keys: [:name,:gsm,:id_no,:profile_picture,:socials])
end