##Вложенные формы с гемом cocoon https://github.com/nathanvda/cocoon
in Gamefile
# for nested form
gem "cocoon", '~> 1.2.0'
делаем bundle install
есть две модели:
class QaQuestion < ActiveRecord::Base
# change table name
self.table_name = "questions"
# for nested form
has_many :pictures, class_name: "QuestionPicture", foreign_key: 'question_id'
accepts_nested_attributes_for :pictures, reject_if: :all_blank, allow_destroy: true
end
class QuestionPicture < ActiveRecord::Base
belongs_to :question, class_name: "QaQuestion", foreign_key: 'question_id'
# paperclip
has_attached_file :picture, {
url: "/question/picture/:attachment/:id_partition/:style/:hash.:extension",
hash_secret: "asdf",
:styles => {
:thumb => ["100x100#",:png],
:medium => ["200x200#",:jpg],
:original => ["800x800", :jpg],
},
:convert_options => {:thumb => Proc.new{Gexcore::ImagesHelpers.convert_options}}
}
validates_attachment_content_type :picture, :content_type => /\Aimage\/.*\Z/
end
есть контроллер
class QaQuestionsController < ApplicationController
...
any_methods_here
...
private
def question_params
params.require(:qa_question).permit(:category_id, :title, :description, :status, :name, :picture,
pictures_attributes: [:id, :description, :picture])
end
end
pictures_attributes из-за того, что мы переименовали в связи между Qaquestion и QuestionPicture
в app/view/qa_question создаем файл с именем (ВАЖНО) _picture_fields.html.haml
имя файла зависит от того как мы назвали не саму вложенную модель, а ее связь (has_many :pictures, class_name: "QuestionPicture", foreign_key: 'question_id'
, гдеforeign_key: 'question_id'
указывает модели QuestionPicture
с каким конкретно ключем ей обращаться к модели QaQuestion
) и заполняем кодом (это наш частный случай):
app/view/qa_question/_picture_fields.html.haml
.nested-fields
%hr
= f.input :picture, as: :file
= f.input :description, as: :text
= link_to_remove_association "remove", f
в app/view/qa_question/_form.html.haml
включаем вложенную форму
= horizontal_simple_form_for(@item, html: { class: 'form-horizontal', multipart: true }) do |f|
= f.error_notification
.input-group
= f.input :title
= f.input :description
%h3 Pictures
#pictures
= f.simple_fields_for :pictures, html: { class: 'form-horizontal' } do |picture|
= render 'picture_fields', f: picture
.links
= link_to_add_association 'add', f, :pictures, class: 'btn btn-primary btn-lg'
%br
= f.button :submit, :class => "btn btn-primary"