0

У меня есть структура 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 и работает, но форма не отображается на Imageenter image description here. Как я могу это исправить?

+0

почему профиль 'belongs_to: image', а не наоборот? – basiam

+0

Чтобы сохранить таблицу 'FK' в 'profiles', а не как' images'. Позднее модель изображения будет использоваться с разными моделями, это не должно быть связано с другими. – 0xDEADBEEF

+0

Я уже пробовал что-то подобное без успеха. :(Я предлагаю вам привязать модель изображения к пользователю. – nistvan

ответ

0

К сожалению, я не нашел правильное решение этой проблемы, и оно по-прежнему актуально (я не собираюсь закрывать этот вопрос, на всякий случай когда-нибудь он ответит).

Но я моделировал поведение, близкое к желаемому.

Итак, к модели 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 добавлен аватар allow_params для пользователя.

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

Смежные вопросы