我正在寻找一个包含两个模型的输入字段的表单-Devise User模型和Profile模型。我希望使用字段创建概要文件模型,并在创建时引用用户模型。
注册新视图
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<!-- Devise Fields for User model -->
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
<%= f.password_field :password, autocomplete: "new-password" %>
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
<!-- Profile model -->
<%= f.fields_for :profile do |g| %>
<%= g.text_field :first_name %>
<%= g.text_field :last_name %>
<% end %>
<%= f.submit "Sign up" %>
<% end %>
用户模型
has_one :profile, dependent: :destroy
attr_accessor :first_name, :last_name
accepts_nested_attributes_for :profile
个人资料模型
belongs_to :user
应用程序控制器
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [ profile_attributes: [:first_name, :last_name]])
end
设备注册控制器(替代)
def new
super do |resource|
resource.build_profile
end
end
以下是Github https://github.com/Goeken/Speech-today
上的代码我应该怎么做?
答案 0 :(得分:1)
我查看了您的github存储库代码,发现您的User模型代码不正确。这是修改后的用户模型-
class User < ApplicationRecord
has_one :profile, dependent: :destroy
# You should not add first_name last_name validation message here,
# because those are profile model attributes, Not user model
#validates_presence_of :first_name, :last_name
accepts_nested_attributes_for :profile
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
其余代码都可以。 我希望它能起作用。