关联定义:
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
不是临时主键!
通过javascript创建oneself
嵌套表单时,单击“隐藏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