Создайте пользовательскую и профильную модель с одинаковой формой в рельсах - PullRequest
0 голосов
/ 02 октября 2018

Я хочу создать форму с полями ввода для двух моделей - Devise User model и Profile model.Я хочу, чтобы модель профиля создавалась с полями, и при создании ссылки на модель пользователя.

Регистрация Новое представление

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

Application Controller

  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

После заполнения формы я получаю сообщение об ошибке.См. Следующее изображение Sign Up error message

Вот код на Github https://github.com/Goeken/Speech-today

Как мне поступить?

1 Ответ

0 голосов
/ 02 октября 2018

Я посмотрел код вашего репозитория на 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

И остальной код в порядке.Я надеюсь, что это сработает.

...