【问题标题】:Create devise user and profile model with same form in rails在 Rails 中创建具有相同形式的设计用户和配置文件模型
【发布时间】:2018-10-02 02:24:14
【问题描述】:

我希望为两个模型创建一个带有输入字段的表单 - 设计用户模型和配置文件模型。我希望使用字段创建配置文件模型,并在创建时引用用户模型。

注册新视图

<%= 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

我该怎么办?

【问题讨论】:

  • 你的控制器里有什么?
  • 检查日志中是否有任何未经允许的参数。如果是这样,问题出在 configure_permitted_pa​​rameters 方法上。 f.fields_for @user.build_profile 也可以替换为 f.fields_for :profile
  • 尝试将&lt;%= f.fields_for @user.build_profile do |g| %&gt;更改为&lt;%= f.fields_for :profile, @user.build_profile do |g| %&gt;
  • 输出相同的错误。
  • @Nezir 我有很多字段,我刚才仔细检查了其中两个是 t.string "first_name", t.string "last_name"

标签: ruby-on-rails devise ruby-on-rails-5


【解决方案1】:

我查看了您的 github 存储库代码,发现您的用户模型代码不正确。这是修改后的用户模型 -

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

其余代码都可以。 我希望它会起作用。

【讨论】:

  • 我没有意识到我的模型已经过验证。如果他们知道那里有其他帮助我的人,那将是有帮助的。谢谢你接听。
  • 谢谢。很高兴知道这一点。我也在贡献你的 github 存储库并提出拉取请求。看看那个。
猜你喜欢
  • 2017-07-18
  • 1970-01-01
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多