rails 6 Разработка устройства пользователя и учетной записи ActiveModel :: UnknownAttributeError (неизвестный атрибут «account» для пользователя.): - PullRequest
0 голосов
/ 12 июня 2019

Привет, у меня есть приложение rails 6, в котором я хочу, чтобы пользователь создал учетную запись при регистрации.

Я использую devise для аутентификации.

У меня есть две модели: User (devise) и учетная запись

class User < ApplicationRecord
  has_merit
  enum role: [:user, :tech, :admin, :manager]
  belongs_to :account
  accepts_nested_attributes_for :account
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :admin
  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :invitable, :registerable,
         :recoverable, :rememberable, :validatable
end

class Account < ApplicationRecord
  has_many :users, dependent: :destroy
  has_many :clients, dependent: :destroy
end

Во время регистрации (регистрация devise) я хочу, чтобы пользовательсоздать учетную запись.

В консоли это работает:

User.create(email: 'test@email.com', password: "test", password_confirmation: "test, account_attributes: {name: "testaccount"})

создает как ожидалось.

но когда я использую форму переднего конца

<h2>Sign up</h2>

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :email,
                required: true,
                autofocus: true,
                input_html: { autocomplete: "email" }%>

    <%=  f.simple_fields_for :accounts do |a| %>
      <%= a.input :name %>
    <% end %>

    <%= f.input :password,
                required: true,
                hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length),
                input_html: { autocomplete: "new-password" } %>
    <%= f.input :password_confirmation,
                required: true,
                input_html: { autocomplete: "new-password" } %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Sign up" %>
  </div>
<% end %>

Я получаю забавную ошибку

ActiveModel::UnknownAttributeError (unknown attribute 'accounts' for User.):

Моя схема

create_table "accounts", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet "current_sign_in_ip"
    t.inet "last_sign_in_ip"
    t.integer "role"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "sash_id"
    t.integer "level", default: 0
    t.bigint "account_id"
    t.index ["account_id"], name: "index_users_on_account_id"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

Ваша помощь очень ценится, и если вам нужна дополнительная информация, пожалуйста, дайте мне знать.

1 Ответ

3 голосов
/ 12 июня 2019

Вы получаете UnknownAttributeError, потому что в вашей таблице users нет столбца с именем accounts.

Я рекомендую вам сделать это так:

#user.rb
has_one :account, inverse_of: :user
accepts_nested_attributes_for :account

#account.rb
belong_to :user

#controller
def new
  @user = User.new
  @user.build_account
end

Источник: https://github.com/plataformatec/simple_form/wiki/Nested-Models#nested-models

...