Ассоциация определена:
class User < ApplicationRecord
# oneself information
has_one :oneself, -> { oneself }, class_name: 'Information', dependent: :nullify
accepts_nested_attributes_for :oneself, allow_destroy: true
# friend information
has_many :friends, -> { friend }, class_name: 'Information', dependent: :nullify
accepts_nested_attributes_for :friends, allow_destroy: true
...
end
class Information < ApplicationRecord
belongs_to :user, optional: true
enum category: { oneself: 1, friend: 2 }
...
end
Определено Controller.action:
class UsersController < ApplicationController
...
def new
@user = User.new
@user.build_oneself # because need show on page loaded
end
...
# strong_params
def user_params
params.require(:user).permit(:name,
oneself_attributes: [:id, :name],
friends_attributes: [:id, :name])
end
end
когда я создаю вложенную форму кокона:
= simple_form_for @user do |f|
...
= f.simple_fields_for :oneself do |of|
= render partial: 'oneself_fields', locals: { f: of }
= f.simple_fields_for :friends do |ff|
= render partial: 'oneself_fields', locals: { f: ff }
= link_to_add_association 'Add friend', f, :friends
= f.submit
HTML и динамическое создание в порядке, но не могут сохранить! Структура данных, как это:
params: {
"name" => xxx,
"oneself_attributes" => {"id" => xxxx, "name" => xxxx},
"friends_attributes" => {"123" => {"id" => xxx, "name" => xxx}},{"456" => {"id" => xxx, "name" => xxx}}
}
Это проблема: build_oneself
не временный первичный ключ !
при создании oneself
вложенной формы с помощью javascript нажмите кнопку скрытия link_to_add_association
, ошибка изменится на Can't save User.oneself not user_id
Я пробовал:
class Information < ApplicationRecord
enum category: { oneself: 1, friend: 2 }
end
class Oneself < Information
attribute :category, :integer, 1
end
class Friend < Information
attribute :category, :integer, 2
end