У меня есть структура User-> Profile-> Image
и вы хотите использовать одну форму для редактирования и записи в ActiveAdmin
. Я использую accepts_nested_attributes_for
в моделях:Форма ActiveAdmin: несколько вложенных форм
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
И такие permit_params
в ActiveAdmin.register User
:
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
и работает, но форма не отображается на Image
. Как я могу это исправить?
почему профиль 'belongs_to: image', а не наоборот? – basiam
Чтобы сохранить таблицу 'FK' в 'profiles', а не как' images'. Позднее модель изображения будет использоваться с разными моделями, это не должно быть связано с другими. – 0xDEADBEEF
Я уже пробовал что-то подобное без успеха. :(Я предлагаю вам привязать модель изображения к пользователю. – nistvan