Ruby on rails 使用Rails在Desive注册表单中嵌套母公司
我想构建我的应用程序,让一个用户属于一家公司,一家公司可以有很多用户。公司名称应包含在我的设计注册表中 这是我的密码: company.rbRuby on rails 使用Rails在Desive注册表单中嵌套母公司,ruby-on-rails,ruby,forms,devise,nested-forms,Ruby On Rails,Ruby,Forms,Devise,Nested Forms,我想构建我的应用程序,让一个用户属于一家公司,一家公司可以有很多用户。公司名称应包含在我的设计注册表中 这是我的密码: company.rb class Company < ApplicationRecord has_many :users end class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable,
class Company < ApplicationRecord
has_many :users
end
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :company
accepts_nested_attributes_for :company
end
class RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
# GET /resource/sign_up
def new
build_resource({})
set_minimum_password_length
resource.build_company
yield resource if block_given?
respond_with self.resource
end
# POST /resource
def create
build_resource(sign_up_params)
resource.save
if resource.persisted?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource, location: new_api_v1_public_members_user_registration_path(beta_token: params[:beta_token])
end
end
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit(:email, :password, :password_confirmation, company: [ :name])
end
end
end
使用上面给出的代码,将所有值提交到我的创建路由(根据我的日志文件)。但是,公司父值未被持久化。这会导致我的表单验证失败,因为Company.name值不能为空
如何将此代码更改为:
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit(:email, :password, :password_confirmation, company: [ :name])
end
end
到
并在user.rb中更改型号<代码>接受公司的\u嵌套\u属性\u
accepts_nested_attributes_for :company, reject_if: :all_blank, allow_destroy: true
我不知道HAML是如何工作的,但我认为f.fields_for block没有尽头
= f.fields_for :company do |c|
= c.text_field :name
= end
试着改变
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit(:email, :password, :password_confirmation, company: [ :name])
end
end
到
并在user.rb中更改型号<代码>接受公司的\u嵌套\u属性\u
accepts_nested_attributes_for :company, reject_if: :all_blank, allow_destroy: true
我不知道HAML是如何工作的,但我认为f.fields_for block没有尽头
= f.fields_for :company do |c|
= c.text_field :name
= end
你试过使用嵌套表单gem吗?你试过使用嵌套表单gem吗?谢谢@luissimo。这修正了我的错误。仅供参考…Haml不需要结束。它使用缩进来确定块。这就是为什么我喜欢使用它,因为我觉得我的代码是干净的Hanks@luissimo。这修正了我的错误。仅供参考…Haml不需要结束。它使用缩进来确定块。这就是为什么我喜欢使用它,因为我觉得我的代码更干净