[英]ActiveAdmin form: multiple nested forms
我有一個結構User-> Profile-> Image
並且想要使用一種表單在ActiveAdmin
進行編輯和記錄。 我在模型中使用accepts_nested_attributes_for
:
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy;
accepts_nested_attributes_for :profile, allow_destroy: true
end
class Profile < ActiveRecord::Base
belongs_to :image, dependent: :destroy;
accepts_nested_attributes_for :image,:reject_if => proc { |attributes| !attributes['img'].present? }, :allow_destroy => true
end
class Image < ActiveRecord::Base
has_attached_file :img
validates_attachment_content_type :img, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
以及ActiveAdmin.register User
此類permit_params
:
permit_params do
permitted=[:id,:login, :email, :admin, :password, :password_confirmation, :ip_address];
permitted.append(profile_attributes:[:name,:second_name,:middle_name,:img,:mobile_phone,:country, :city,:region, image_attributes:[:img]]);
permitted
end
最后,代碼本身形成
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "User Details" do
f.input :login
f.input :email
f.input :password
f.input :password_confirmation
end
f.inputs "Profile", for: [:profile, f.object.profile || f.object.build_profile] do |pf|
pf.input :name
pf.input :second_name
pf.input :middle_name
pf.input :mobile_phone, :as => :phone
pf.input :country, selected: "RU"
pf.input :city
pf.input :region
pf.inputs "Avatar", for:[:image, pf.object.image || pf.object.build_image] do |fpf|
fpf.input :img, :as => :file
end
end
f.inputs "User Perference" do
f.input :admin, type: :boolean
end
f.actions
end
不幸的是,此代碼無法正常工作:該表單已與Profile
和Work一起正確顯示,但是該表單對Image
不可見 。 我怎樣才能解決這個問題?
不幸的是,我沒有找到解決該問題的正確方法,它仍然很重要(我不會結束這個問題,以防萬一有一天它能回答)。
但是我對行為進行了建模,使其接近所需的行為。
因此,在User
模型中,我為各個對象添加了Avatar
-interface。
def avatar
if self.profile && self.profile.image
self.profile.image.img
else
nil
end
end
def avatar=(arg)
unless self.profile.image
self.profile.create_image(img:arg)
else
self.profile.image.update_attributes(img:arg)
end
self.profile.image
end
def avatar?
if self.profile && self.profile.image
!self.profile.image.img.nil?
else
nil
end
end
在ActiveAdmin中,添加到用戶的頭像允許使用的參數。
permit_params ..., :avatar
最后,以添加的文件字段的形式:
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "User Details" do
#Fields for User
end
f.inputs "profile", for: [:profile, f.object.profile || f.object.build_profile] do |pf|
#Fields for profile
end
f.inputs "Avatar" do
f.input :avatar, as: :file
end
f.actions
end
值得注意的是,如果在提交表單時觀察到異常行為(值為空),則應注意accepts_nested_attributes_for
的參數,尤其是update_only
和reject_if
。
我仍在等待ActiveAdmin中多個嵌套表單的常規解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.