Предположим у меня приложение-опросник, poll имеет много questions, они имеют много answers, все соединены друг с другом через accepts_nested_attributes_for
Клиент взаимодействует с сервером через json-api, заполняет в форме все поля, нажимает на save, данные отправляются на create
def create
@poll = current_user.polls.create(poll_params)
if @poll.persisted?
render 'show', status: :created
else
render json: { errors: @poll.errors }, status: :internal_server_error
end
end
private
def poll_params
params.require(:poll).permit(
:title,
# has many
{
questions: [
:id,
:content,
{
# has many
:options => [:id, :content]
}
]
}
)
end
Вопрос в том, что делать, если на странице edit
, клиент решит удалить некоторые поля? Новые данные при сохранении отправляются на update
(@poll.update_attributes(poll_params)
) и там я должен удалять все вложения poll кроме самого poll и заново их создавать? или в запросе должно быть особое поле deleted_attr
с типом и id всех удаленных полей?
Данные должны отправляться одним запросом, ведь вдруг клиент при форматировании решит аннулировать удаление поля
Модели
class Poll < ActiveRecord::Base
belongs_to :user
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
# alias
def questions=(value)
value.is_a?(Array) && value.first.is_a?(Hash) ? (self.questions_attributes = value) : super
end
end
class Question < ActiveRecord::Base
belongs_to :poll
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
# alias
def answers=(value)
value.is_a?(Array) && value.first.is_a?(Hash) ? (self.answers_attributes = value) : super
end
end
class Answer < ActiveRecord::Base
belongs_to :question
acts_as_voteable # thumbs_up gem
end